-
Notifications
You must be signed in to change notification settings - Fork 3
/
Iterative-Inorder_Preorder_PostOrder_Traversal
103 lines (92 loc) · 2.37 KB
/
Iterative-Inorder_Preorder_PostOrder_Traversal
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.tree.traversal.iterative;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class IterativeTreeTraversal {
static List<Integer> result;
public static void main(String[] args) {
TreeNode left = new TreeNode(2);
TreeNode right = new TreeNode(3);
TreeNode root = new TreeNode(1, left, right);
left.left = new TreeNode(4);
left.right = new TreeNode(5);
right.left = new TreeNode(6);
right.right = new TreeNode(7);
result = new ArrayList<Integer>();
System.out.println("Preorder Traversal : " + preorderTraversal(root));
result = new ArrayList<Integer>();
System.out.println("Inorder Traversal : " + inorderTraversal(root));
result = new ArrayList<Integer>();
System.out.println("Postorder Traversal : " + postorderTraversal(root));
}
private static List<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode current = root;
while(true) {
while(current != null) {
stack.push(current);
current = current.left;
}
if(stack.isEmpty()) break;
current = stack.pop();
result.add(current.val);
current = current.right;
}
return result;
}
private static List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode current = root;
while(true) {
while(current != null) {
result.add(current.val);
stack.push(current);
current = current.left;
}
if(stack.isEmpty()) break;
current = stack.pop();
current = current.right;
}
return result;
}
private static List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode current = root;
TreeNode previous = null;
while(true){
while(current != null) {
stack.push(current);
current = current.left;
}
if(stack.isEmpty()) break;
while(current == null && !stack.isEmpty()) {
current = stack.peek();
if(current.right == null || current.right == previous) {
result.add(current.val);
stack.pop();
previous = current;
current = null;
}
else {
current = current.right;
}
}
}
return result;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}