This repository was archived by the owner on Apr 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathPostOrderTraversal.java
More file actions
64 lines (45 loc) · 1.48 KB
/
PostOrderTraversal.java
File metadata and controls
64 lines (45 loc) · 1.48 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
/*----- Post Order Traversal in a Tree -----*/
import java.util.*;
class Node{
Node left,right;
int dValue;
Node(int v){
dValue = v;
left = null;
right = null;
}
}
public class PostOrderTraversal {
public static ArrayList<Integer> postorderTraversal(Node A) {
ArrayList<Integer> list = new ArrayList<>();
Stack<Node> stack = new Stack<>();
Stack<Integer> stackReverse = new Stack<>();
stack.push(A);
while(!stack.empty()){
Node node = stack.peek();
int data = stack.pop().dValue;
stackReverse.push(data);
if(node.left!=null)
stack.push(node.left);
if(node.right!=null)
stack.push(node.right);
}
while(!stackReverse.empty()){
list.add(stackReverse.pop());
}
return list;
}
public static void main(String args[]){
Node root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(50);
root.right.left = new Node(60);
root.right.right = new Node(70);
ArrayList<Integer> list = postorderTraversal(root);
for(int i=0; i<list.size(); i++){
System.out.print(list.get(i)+" ");
}
}
}