forked from architsingla13/InterviewBit-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostOrder.java
More file actions
41 lines (32 loc) · 857 Bytes
/
PostOrder.java
File metadata and controls
41 lines (32 loc) · 857 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
34
35
36
37
38
39
40
41
package Trees;
import java.util.ArrayList;
import java.util.Stack;
/**
* Author - archit.s
* Date - 04/11/18
* Time - 11:14 PM
*/
public class PostOrder {
public ArrayList<Integer> postorderTraversal(TreeNode A) {
Stack<TreeNode> s = new Stack<>();
TreeNode lastVisited = null;
ArrayList<Integer> r = new ArrayList<>();
while(!s.empty() || A!=null){
if(A!=null){
s.push(A);
A = A.left;
}
else{
TreeNode topNode = s.peek();
if(topNode.right!=null && topNode.right!=lastVisited){
A = topNode.right;
}
else{
r.add(topNode.val);
lastVisited = s.pop();
}
}
}
return r;
}
}