forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBSTIterator.java
40 lines (33 loc) · 861 Bytes
/
BSTIterator.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
import java.util.Stack;
public class BSTIterator {
private Stack<TreeNode> mStack;
private TreeNode mCurNode;
public BSTIterator(TreeNode root) {
mStack = new Stack<>();
mCurNode = root;
}
/**
* @return whether we have a next smallest number
*/
public boolean hasNext() {
return !mStack.isEmpty() || mCurNode != null;
}
/**
* @return the next smallest number
*/
public int next() {
int result = -1;
while (hasNext()) {
if (mCurNode != null) {
mStack.push(mCurNode);
mCurNode = mCurNode.left;
} else {
mCurNode = mStack.pop();
result = mCurNode.val;
mCurNode = mCurNode.right;
break;
}
}
return result;
}
}