-
Notifications
You must be signed in to change notification settings - Fork 1
/
LeetCode-173-Binary-Search-Tree-Iterator.java
100 lines (85 loc) · 2.27 KB
/
LeetCode-173-Binary-Search-Tree-Iterator.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/*
In order traversal
*/
class BSTIterator {
Stack<TreeNode> stack;
TreeNode curr;
public BSTIterator(TreeNode root) {
stack = new Stack<>();
curr = root;
}
/** @return the next smallest number */
public int next() {
int next = 0;
// This if is not necessary, as we are sure "curr" is out from a stack.
// if (curr != null || !stack.isEmpty()) {
// push all the left nodes into the stack
while(curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
next = curr.val;
curr = curr.right;
// }
return next;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return curr != null || !stack.isEmpty();
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/
/**
Morris pre-order traversal
Space: O(1)
Time: O(N)
*/
class BSTIterator {
TreeNode curr;
public BSTIterator(TreeNode root) {
curr = root;
}
public int next() {
int next = 0;
while (curr != null) {
if (curr.left == null) {
next = curr.val;
curr = curr.right;
break;
} else {
TreeNode predecessor = curr.left;
while (predecessor.right != null && predecessor.right != curr) {
predecessor = predecessor.right;
}
if (predecessor.right == null) {
predecessor.right = curr;
curr = curr.left;
} else {
next = curr.val;
predecessor.right = null;
curr = curr.right;
break;
}
}
}
return next;
}
public boolean hasNext() {
return curr != null;
}
}