Leetcode - 226. Invert Binary Tree
Leetcode - 226. Invert Binary Tree
- Given the root of a binary tree, invert the tree, and return its root.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
func invertTree(root *TreeNode) *TreeNode {
if root == nil{
return root
}
tmp := root.Left
root.Left = root.Right
root.Right = tmp
invertTree(root.Left)
invertTree(root.Right)
return root
}
Another approach…
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func invertTree(root *TreeNode) *TreeNode {
traverse(root)
return root
}
func traverse(root *TreeNode){
if root == nil{
return
}
left := root.Left
right := root.Right
root.Left = right
root.Right = left
traverse(root.Left)
traverse(root.Right)
}
This post is licensed under CC BY 4.0 by the author.