Skip to content

Commit c6f6c31

Browse files
committed
binary_tree_postorder_traversal
1 parent 2e2369a commit c6f6c31

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
128128
#### [142. Linked List Cycle II](https://github.com/hitzzc/go-leetcode/tree/master/linked_list_cycle_II)
129129
#### [143. reorder list](https://github.com/hitzzc/go-leetcode/tree/master/reorder_list)
130130
#### [144. binary tree preorder traversal](https://github.com/hitzzc/go-leetcode/tree/master/binary_tree_preorder_traversal)
131+
#### [145. binary tree postorder traversal](https://github.com/hitzzc/go-leetcode/tree/master/binary_tree_postorder_traversal)
131132

132133

133134

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package binary_tree_postorder_traversal
2+
3+
type TreeNode struct {
4+
Val int
5+
Left *TreeNode
6+
Right *TreeNode
7+
}
8+
9+
func postorderTraversal(root *TreeNode) []int {
10+
rets := []int{}
11+
if root == nil {
12+
return rets
13+
}
14+
stack := []*TreeNode{root}
15+
head := root
16+
for len(stack) != 0 {
17+
node := stack[len(stack)-1]
18+
if node.Left == head || node.Right == head || node.Left == nil && node.Right == nil {
19+
rets = append(rets, node.Val)
20+
stack = stack[:len(stack)-1]
21+
head = node
22+
} else {
23+
if node.Right != nil {
24+
stack = append(stack, node.Right)
25+
}
26+
if node.Left != nil {
27+
stack = append(stack, node.Left)
28+
}
29+
}
30+
}
31+
return rets
32+
}

0 commit comments

Comments
 (0)