-
Notifications
You must be signed in to change notification settings - Fork 15
/
implement-iterator-of-binary-search-tree.java
115 lines (101 loc) · 3.2 KB
/
implement-iterator-of-binary-search-tree.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// in 12 mins. + in-order review.
// in 20 mins for Morris version.
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
* Example of iterat a tree:
* Solution iterator = new Solution(root);
* while (iterator.hasNext()) {
* TreeNode node = iterator.next();
* do something for node
* }
*/
public class Solution {
//@param root: The root of binary tree.
Stack<TreeNode> st = new Stack<TreeNode>();
TreeNode runner = null;
public Solution(TreeNode root) {
// write your code here
runner = root;
// st.push(root);
}
//@return: True if there has next node, or false
public boolean hasNext() {
// write your code here
return (!st.isEmpty() || runner != null);
}
//@return: return next node
public TreeNode next() {
// write your code here
while (runner != null) {
st.push(runner);
runner = runner.left;
}
TreeNode res = st.pop();
runner = res.right;
return res;
}
}
/// Morris traversal: O(1) space.
public class Solution {
//@param root: The root of binary tree.
TreeNode runner = null;
public Solution(TreeNode root) {
// write your code here
runner = root;
}
//@return: True if there has next node, or false
public boolean hasNext() {
// write your code here
// using morris traversal we make sure
// runner pointer will always not be null
// untill traversal is done.
return runner != null;
}
//@return: return next node
public TreeNode next() {
// first check left subtree, if null then we visit
// current node and move to its right subtree.
if (runner.left == null) {
// visit runner
TreeNode res = runner;
runner = runner.right;
return res;
} else {
// if left subtree not null, means we either
// havent visit the substree or current node.
//
// first while loop continues untill we find next
// in-order element.
while (runner.left != null) {
// check whether predecessor's right pointer
// points to current node.
TreeNode pre = runner.left;
while (pre.right != null && pre.right != runner) {
pre = pre.right;
}
if (pre.right == runner) {
// already visited left subtree. visit current node.
pre.right = null;
TreeNode res = runner;
runner = runner.right;
return res;
} else {
// visit left subtree first.
pre.right = runner;
runner = runner.left;
}
}
TreeNode res = runner;
runner = runner.right;
return res;
}
}
}