NOTE
Invert Binary Tree
LeetCode notes on Invert Binary Tree.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Problem Description
Invert a binary tree.
2. Approach
- Approach 1
- Preorder traversal
- Swap the left and right subtrees
- Apply the same operation recursively to the left and right subtrees
3. Implementation
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
root.Left, root.Right = root.Right, root.Left
invertTree(root.Left)
invertTree(root.Right)
return root
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub