-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathIterativeInOrderTraversal.java
96 lines (83 loc) · 2.44 KB
/
IterativeInOrderTraversal.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
/*
This performs iterative in-order traversal
through a binary search tree.
In a binary search tree, for ever node v:
- Elements in left subtree rooted at v
are less than element stored at v.
- Elements in right subtree rooted at v
are greater than or equal to one at v.
Let n be the number of nodes in the
binary search tree.
Time complexity: O(n)
Space complexity: O(1)
*/
import java.util.function.Consumer;
public class IterativeInOrderTraversal {
private BTNode BTRoot;
public IterativeInOrderTraversal() {
/*
* Create tree below:
* * 4
* / \
* 2 7
* * / \
* * 6 8
*/
BTRoot = new BTNode(4, null, null, null);
BTNode rootLeft = new BTNode(2, null, null, BTRoot);
BTRoot.left = rootLeft;
BTNode rootRight = new BTNode(7, null, null, BTRoot);
BTRoot.right = rootRight;
BTNode rootRightLeft = new BTNode(6, null, null, rootRight);
BTNode rootRightRight = new BTNode(8, null, null, rootRight);
rootRight.left = rootRightLeft;
rootRight.right = rootRightRight;
}
public static void main(String[] args) {
IterativeInOrderTraversal application = new IterativeInOrderTraversal();
// The in-order traversal yields a sorted list
application.iterativeInOrderTraversal((node) -> {
System.out.print(node.val + " ");
}); // 2 4 6 7 8
}
// Use three pointers to traverse the tree iteratively
public void iterativeInOrderTraversal(
Consumer<BTNode> callback) {
if (BTRoot == null) {
return;
}
BTNode currentNode = BTRoot, previousNode = null;
BTNode nextNode;
while (currentNode != null) {
if (previousNode == null || previousNode == currentNode.parent) {
if (currentNode.left != null) {
nextNode = currentNode.left;
} else {
callback.accept(currentNode);
nextNode = (currentNode.right != null) ? currentNode.right : currentNode.parent;
}
} else if (previousNode == currentNode.left) {
callback.accept(currentNode);
nextNode = (currentNode.right != null) ? currentNode.right : currentNode.parent;
} else {
nextNode = currentNode.parent;
}
previousNode = currentNode;
currentNode = nextNode;
}
}
// Class representing a binary tree node
// with pointers to value, left, right, and parent nodes
private class BTNode {
int val;
BTNode left;
BTNode right;
BTNode parent;
public BTNode(int val, BTNode left, BTNode right, BTNode parent) {
this.val = val;
this.left = left;
this.right = right;
this.parent = parent;
}
}
}