-
Notifications
You must be signed in to change notification settings - Fork 688
/
BinaryTreeIterator.java
90 lines (68 loc) · 1.98 KB
/
BinaryTreeIterator.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
package trees;
import java.util.Stack;
public class BinaryTreeIterator {
/*
* Implement a class that implements an InOrder Iterator on a Binary Tree
*
* */
private static class Node {
private int data;
private Node left, right;
Node(int item) {
data = item;
left = right = null;
}
public int getData() {
return data;
}
public Node getLeft() {
return left;
}
public Node getRight() {
return right;
}
}
private Node root1;
private class InOrderTreeIterator {
private Stack<Node> stk = new Stack();
public InOrderTreeIterator(Node root) {
while (root != null) {
stk.push(root);
root = root.left;
}
}
public boolean hasNext() {
return !stk.isEmpty();
}
public Node getNext() {
if (stk.isEmpty())
return null;
Node rVal = stk.pop();
Node temp = rVal.right;
while (temp != null) {
stk.push(temp);
temp = temp.left;
}
return rVal;
}
}
public void inOrderUsingIterator(Node root) {
InOrderTreeIterator iterator = new InOrderTreeIterator(root);
while (iterator.hasNext()) {
System.out.print(iterator.getNext().data + ", ");
}
System.out.println();
}
public static void main(String[] args) {
BinaryTreeIterator tree = new BinaryTreeIterator();
tree.root1 = new Node(100);
tree.root1.left = new Node(50);
tree.root1.right = new Node(200);
tree.root1.left.left = new Node(25);
tree.root1.left.right = new Node(75);
tree.root1.right.left = new Node(125);
tree.root1.right.right = new Node(350);
tree.inOrderUsingIterator(tree.root1);
System.out.println();
}
}