-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path145-postOrder.java
More file actions
45 lines (39 loc) · 1.11 KB
/
145-postOrder.java
File metadata and controls
45 lines (39 loc) · 1.11 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
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution_145 {
List<Integer> res = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
postOrder(root);
return res;
}
// 递归算法
void postOrder(TreeNode root) {
if(root == null) return;
postOrder(root.left);
postOrder(root.right);
res.add(root.val);
}
// 非递归算法
public List<Integer> postorderTraversal_2(TreeNode root) {
Stack<TreeNode> cur = new Stack<>();
if(root!=null) cur.push(root);
TreeNode pre = null;
while(!cur.isEmpty()) {
TreeNode c = cur.peek();
if((c.left==null && c.right==null) || (pre != null && (pre == c.left || pre == c.right))) {
res.add(c.val);
pre = c;
cur.pop();
} else {
if(c.right != null) cur.push(c.right);
if(c.left != null) cur.push(c.left);
}
}
return res;
}
}