-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathBinaryTree.java
98 lines (86 loc) · 3.04 KB
/
BinaryTree.java
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
package Tree;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class BinaryTree {
BinaryTreeNode root;
BinaryTree() {
}
BinaryTree(int d) {
root = new BinaryTreeNode(d);
}
/* Recursive approach of inOrder Traversal of Tree
* Time Complexity: O(n)
* Space Complexity: O(n) (implicit)
*/
public void inOrder(BinaryTreeNode root) {
if (root == null) return;
inOrder(root.left);
System.out.print(root.data + " ");
inOrder(root.right);
}
/* Iterative approach of inOrder Traversal of Tree
* Time Complexity: O(n)
* Space Complexity: O(n) (explicit)
*/
public void inOrderWithoutRecursion(BinaryTreeNode root) {
if (root == null) return;
Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
while (root != null) {
stack.push(root);
root = root.left;
}
while (!stack.empty()) {
BinaryTreeNode temp = stack.pop();
System.out.print(temp.data + " ");
if (temp.right != null)
root = temp.right;
while (root != null) {
stack.push(root);
root = root.left;
}
}
}
/* inOrder Traversal of Tree with using any extra space, Morris Traversal
* Time Complexity: O(n)
* Space Complexity: O(1)
*/
public void inOrderMorrisTraversal(BinaryTreeNode root) {
while (root != null) {
if (root.left == null) {
System.out.print(root.data + " ");
root = root.right;
} else {
BinaryTreeNode prev = root.left;
while (prev.right != null && prev.right != root)
prev = prev.right;
if (prev.right == null) {
prev.right = root;
root = root.left;
} else {
prev.right = null;
System.out.print(root.data + " ");
root = root.right;
}
}
}
}
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();
binaryTree.root = new BinaryTreeNode(1);
binaryTree.root.left = new BinaryTreeNode(2);
binaryTree.root.right = new BinaryTreeNode(3);
binaryTree.root.left.left = new BinaryTreeNode(4);
binaryTree.root.left.right = new BinaryTreeNode(5);
binaryTree.root.right.right = new BinaryTreeNode(6);
binaryTree.root.left.left.right = new BinaryTreeNode(7);
binaryTree.root.left.right.left = new BinaryTreeNode(8);
binaryTree.root.right.right.left = new BinaryTreeNode(9);
System.out.println("\nInOrder");
binaryTree.inOrder(binaryTree.root);
System.out.println("\nInOrderWithoutRecurion");
binaryTree.inOrderWithoutRecursion(binaryTree.root);
System.out.println("\nInOrderMorrisTraversal");
binaryTree.inOrderMorrisTraversal(binaryTree.root);
}
}