-
Notifications
You must be signed in to change notification settings - Fork 229
Expand file tree
/
Copy pathL12_iterativePostOrder1StackJava
More file actions
31 lines (27 loc) · 968 Bytes
/
L12_iterativePostOrder1StackJava
File metadata and controls
31 lines (27 loc) · 968 Bytes
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
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> st1 = new Stack<TreeNode>();
List<Integer> postOrder = new ArrayList<Integer>();
if(root == null) return postOrder;
TreeNode current = root;
while(current != null || !st1.isEmpty()) {
if(current != null){
st1.push(current);
current = current.left;
}else{
TreeNode temp = st1.peek().right;
if (temp == null) {
temp = st1.pop();
postOrder.add(temp.val);
while (!st1.isEmpty() && temp == st1.peek().right) {
temp = st1.pop();
postOrder.add(temp.val);
}
} else {
current = temp;
}
}
}
return postOrder;
}
}