forked from szl0072/Leetcode-Solution-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTreeIterator.java
More file actions
46 lines (40 loc) · 971 Bytes
/
BinarySearchTreeIterator.java
File metadata and controls
46 lines (40 loc) · 971 Bytes
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
package leetcode;
import java.util.Stack;
/**
* Project Name : Leetcode
* Package Name : leetcode
* File Name : BinarySearchTreeIterator
* Creator : Edward
* Date : Sep, 2017
* Description : TODO
*/
public class BinarySearchTreeIterator {
/**
* 173. Binary Search Tree Iterator
*
* time : O(n)
* @param root
*/
private TreeNode cur;
private Stack<TreeNode> stack;
public BinarySearchTreeIterator(TreeNode root) {
cur = root;
stack = new Stack<>();
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if (!stack.isEmpty() || cur != null) return true;
return false;
}
/** @return the next smallest number */
public int next() {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
int val = cur.val;
cur = cur.right;
return val;
}
}