Skip to content

Commit ce0e190

Browse files
author
legolas.zhan
committed
590: use stack instead of recursive
1 parent 87197a0 commit ce0e190

File tree

1 file changed

+27
-10
lines changed

1 file changed

+27
-10
lines changed

leetcode/tree/postorder.go

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -27,18 +27,35 @@ type Node struct {
2727
}
2828

2929
func postorder(root *Node) []int {
30-
var helper func(root *Node, ans *[]int)
31-
helper = func(root *Node, ans *[]int) {
32-
if root == nil {
33-
return
34-
}
35-
for _, child := range root.Children {
36-
helper(child, ans)
30+
// var helper func(root *Node, ans *[]int)
31+
// helper = func(root *Node, ans *[]int) {
32+
// if root == nil {
33+
// return
34+
// }
35+
// for _, child := range root.Children {
36+
// helper(child, ans)
37+
// }
38+
// *ans = append(*ans, root.Val)
39+
// }
40+
41+
// ans := []int{}
42+
// helper(root, &ans)
43+
// return ans
44+
45+
ans := []int{}
46+
stack := []*Node{root}
47+
for len(stack) != 0 {
48+
cur := stack[len(stack)-1]
49+
ans = append(ans, cur.Val)
50+
stack = stack[:len(stack)-1]
51+
for _, child := range cur.Children {
52+
stack = append(stack, child)
3753
}
38-
*ans = append(*ans, root.Val)
3954
}
4055

41-
ans := []int{}
42-
helper(root, &ans)
56+
for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 {
57+
ans[i], ans[j] = ans[j], ans[i]
58+
}
59+
4360
return ans
4461
}

0 commit comments

Comments
 (0)