-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path145-BinaryTreePostorderTraversal.go
More file actions
105 lines (92 loc) · 2.24 KB
/
145-BinaryTreePostorderTraversal.go
File metadata and controls
105 lines (92 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
// 145. Binary Tree Postorder Traversal
// Given the root of a binary tree, return the postorder traversal of its nodes' values.
// Example 1:
// <img src="https://assets.leetcode.com/uploads/2020/08/28/pre1.jpg" />
// Input: root = [1,null,2,3]
// Output: [3,2,1]
// Example 2:
// Input: root = []
// Output: []
// Example 3:
// Input: root = [1]
// Output: [1]
// Constraints:
// The number of the nodes in the tree is in the range [0, 100].
// -100 <= Node.val <= 100
// Follow up: Recursive solution is trivial, could you do it iteratively?
import "fmt"
// Definition for a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 递归处理
func postorderTraversal(root *TreeNode) []int {
var res []int
postorder(root, &res)
return res
}
// 递归
func postorder (root *TreeNode, output *[]int) {
if root != nil {
postorder(root.Left, output)
postorder(root.Right, output)
// 后序遍历
*output = append(*output, root.Val)
}
}
// 迭代处理
func postorderTraversal1(root *TreeNode) (res []int) {
// 递归的时候隐式地维护了一个栈,而在迭代的时候需要显式地将这个栈模拟出来
stack := []*TreeNode{}
var prev *TreeNode
for root != nil || len(stack) > 0 {
for root != nil {
stack = append(stack, root)
root = root.Left
}
root = stack[len(stack)-1]
stack = stack[:len(stack)-1]
if root.Right == nil || root.Right == prev {
res = append(res, root.Val)
prev = root
root = nil
} else {
stack = append(stack, root)
root = root.Right
}
}
return
}
func main() {
tree1 := &TreeNode {
1,
nil,
&TreeNode {
2,
&TreeNode{3, nil, nil},
nil,
},
}
tree3 := &TreeNode {
1,
nil,
nil,
}
fmt.Println(postorderTraversal(tree1)) // [3,2,1]
fmt.Println(postorderTraversal(nil)) // []
fmt.Println(postorderTraversal(tree3)) // [1]
fmt.Println(postorderTraversal1(tree1)) // [3,2,1]
fmt.Println(postorderTraversal1(nil)) // []
fmt.Println(postorderTraversal1(tree3)) // [1]
}