-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode145.java
More file actions
103 lines (93 loc) · 2.94 KB
/
LeetCode145.java
File metadata and controls
103 lines (93 loc) · 2.94 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
import java.util.LinkedList;
import java.util.List;
import java.util.Deque;
import util.TreeNode;
public class LeetCode145 {
public static void main(String[] args) {
// 输入:root = [1,null,2,3]
// 输出:[3,2,1]
System.out.println(new Solution145_2().postorderTraversal(TreeNode.buildTree(new Integer[] { 1, null, 2, 3 })));
// 输入:root = []
// 输出:[]
System.out.println(new Solution145_2().postorderTraversal(TreeNode.buildTree(new Integer[] {})));
// 输入:root = [1]
// 输出:[1]
System.out.println(new Solution145_2().postorderTraversal(TreeNode.buildTree(new Integer[] { 1 })));
}
}
class Solution145_1 {
// NOTE: 递归版本
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
postorder(root, res);
return res;
}
public void postorder(TreeNode node, List<Integer> res) {
if (node == null) {
return;
}
postorder(node.left, res);
postorder(node.right, res);
res.add(node.val);
}
}
class Solution145_2 {
// NOTE: 前序遍历左右节点调换后整个颠倒
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
Deque<TreeNode> stack = new LinkedList<>();
if (root == null) {
return res;
}
stack.push(root);
while (!stack.isEmpty()) {
TreeNode cur = stack.pop();
res.add(0, cur.val);
if (cur.left != null) {
stack.push(cur.left);
}
if (cur.right != null) {
stack.push(cur.right);
}
}
return res;
}
}
class Solution145_3 {
// NOTE: 传统的迭代版本
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
Deque<TreeNode> stack = new LinkedList<>();
if (root == null) {
return res;
}
TreeNode pre = null;
stack.push(root);
while (!stack.isEmpty()) {
TreeNode cur = stack.peek();
if (pre == null || pre.left == cur || pre.right == cur) {
// 前一个访问的是父节点
if (cur.left != null) {
stack.push(cur.left);
} else if (cur.right != null) {
stack.push(cur.right);
} else {
stack.pop();
res.add(cur.val);
}
} else if (cur.left == pre) {
if (cur.right != null) {
stack.push(cur.right);
} else {
res.add(cur.val);
stack.pop();
}
} else {
res.add(cur.val);
stack.pop();
}
pre = cur;
}
return res;
}
}