-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path145_BinaryTreePostorderTraversal.java
More file actions
85 lines (81 loc) · 2.21 KB
/
145_BinaryTreePostorderTraversal.java
File metadata and controls
85 lines (81 loc) · 2.21 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
/*
* Given a binary tree, return the postorder traversal of its nodes' values.
* For example:
* Given binary tree {1,#,2,3},
* 1
* \
* 2
* /
* 3
* return [3,2,1].
* Note: Recursive solution is trivial, could you do it iteratively?
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//Recursive
public class Solution {
ArrayList<Integer> res = new ArrayList<Integer>();
public List<Integer> postorderTraversal(TreeNode root) {
traverse(root);
return res;
}
private void traverse(TreeNode node) {
if(node == null) return;
traverse(node.left);
traverse(node.right);
res.add(node.val);
}
}
//modified preorder 666
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode temp = stack.pop();
if(temp != null) {
res.add(temp.val);
stack.push(temp.left);
stack.push(temp.right);
}
}
Collections.reverse(res);
return res;
}
}
//iterative 思路厉害
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer>();
TreeNode node = root;
Stack<TreeNode> stack = new Stack<TreeNode>();
Stack<Boolean> status = new Stack<Boolean>();
while(!stack.isEmpty() || node!=null) {
if(node!=null) {
status.push(true);
stack.push(node);
node = node.left;
} else{
node = stack.peek();
boolean flag = status.pop();
if(flag) {
node = node.right;
status.push(false);
} else {
res.add(node.val);
stack.pop();
node = null;
}
}
}
return res;
}
}