forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BSTIterator.java
59 lines (47 loc) · 1.35 KB
/
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.util.Stack;
public class BSTIterator {
private Stack<TreeNode> mStack;
private TreeNode mCurNode;
public BSTIterator(TreeNode root) {
mStack = new Stack<TreeNode>();
mCurNode = root;
// for (mCurNode = root; mCurNode != null; mCurNode = mCurNode.left) {
// mStack.push(mCurNode);
// }
}
/**
* @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;
}
/** 这样写也好,不过要注意在构造函数中初始化如上注释部分
public int next() {
if (mCurNode == null) {
mCurNode = mStack.pop();
}
int val = mCurNode.val;
for (mCurNode = mCurNode.right; mCurNode != null; mCurNode = mCurNode.left) {
mStack.push(mCurNode);
}
return val;
}*/
}