-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostOrderItr.java
More file actions
33 lines (31 loc) · 924 Bytes
/
postOrderItr.java
File metadata and controls
33 lines (31 loc) · 924 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
32
33
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode lastNodeVisited = null;
while(!stack.isEmpty() || root != null){
if(root != null){
stack.push(root);
root = root.left;
} else {
TreeNode peek = stack.peek();
if(peek.right != null && lastNodeVisited != peek.right){
root = peek.right;
} else {
result.add(peek.val);
lastNodeVisited = stack.pop();
}
}
}
return result;
}
}