forked from Nidhi-Sharma9419/Elite-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostorderTraversal.java
More file actions
66 lines (55 loc) · 1.84 KB
/
PostorderTraversal.java
File metadata and controls
66 lines (55 loc) · 1.84 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
package Tree;
import java.util.*;
class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
left = null;
right = null;
}
}
class Binary2 {
static ArrayList < Integer > postOrderTrav(Node cur) {
ArrayList < Integer > postOrder = new ArrayList < > ();
if (cur == null) return postOrder;
Stack < Node > st = new Stack < > ();
while (cur != null || !st.isEmpty()) {
if (cur != null) {
st.push(cur);
cur = cur.left;
} else {
Node temp = st.peek().right;
if (temp == null) {
temp = st.peek();
st.pop();
postOrder.add(temp.data);
while (!st.isEmpty() && temp == st.peek().right) {
temp = st.peek();
st.pop();
postOrder.add(temp.data);
}
} else cur = temp;
}
}
return postOrder;
}
public static void main(String args[]) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.left.right.left = new Node(8);
root.right.left = new Node(6);
root.right.right = new Node(7);
root.right.right.left = new Node(9);
root.right.right.right = new Node(10);
ArrayList < Integer > postOrder = new ArrayList < > ();
postOrder = postOrderTrav(root);
System.out.println("The postOrder Traversal is : ");
for (int i = 0; i < postOrder.size(); i++) {
System.out.print(postOrder.get(i) + " ");
}
}
}