Skip to content

Commit 184fde9

Browse files
committed
add another solution of Invert Binary Tree
1 parent 5f15e87 commit 184fde9

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

go/invert_binary_tree.go

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,28 @@
11
//lint:file-ignore U1000 Ignore all unused code
22
package main
33

4-
func invertTree(root *TreeNode) *TreeNode {
4+
func invertTreeRecursive(root *TreeNode) *TreeNode {
55
if root != nil {
6-
root.Left, root.Right = invertTree(root.Right), invertTree(root.Left)
6+
root.Left, root.Right = invertTreeRecursive(root.Right), invertTreeRecursive(root.Left)
7+
}
8+
return root
9+
}
10+
11+
func invertTreeIterative(root *TreeNode) *TreeNode {
12+
if root == nil {
13+
return nil
14+
}
15+
stack := []*TreeNode{root}
16+
for len(stack) > 0 {
17+
node := stack[len(stack)-1]
18+
stack = stack[:len(stack)-1]
19+
node.Left, node.Right = node.Right, node.Left
20+
if node.Left != nil {
21+
stack = append(stack, node.Left)
22+
}
23+
if node.Right != nil {
24+
stack = append(stack, node.Right)
25+
}
726
}
827
return root
928
}

0 commit comments

Comments
 (0)