-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathBSTIterator2.java
77 lines (67 loc) · 1.91 KB
/
BSTIterator2.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
package leetcode.algo.design.leet_zh_173;
import leetcode.algo.tree.base.TreeNode;
import leetcode.algo.tree.leet_zh_1167.Codec;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator2 {
/*
*
* 173. 二叉搜索树迭代器
*
* 空间复杂度O(1),next()平均时间复杂度O(1)
* 执行用时 : 140 ms, 在Binary Search Tree Iterator的Java提交中击败了71.25% 的用户
* 内存消耗 : 67.9 MB, 在Binary Search Tree Iterator的Java提交中击败了5.07% 的用户
* */
private TreeNode node;
public BSTIterator2(TreeNode root) {
node = root;
}
/**
* @return the next smallest number
*/
public int next() {
while (node != null) {
if (node.left != null) {
TreeNode tmp = node.left;
while (tmp.right != null) tmp = tmp.right;
tmp.right = node;
tmp = node.left;
node.left = null;
node = tmp;
} else {
int next = node.val;
node = node.right;
return next;
}
}
return -1;
}
/**
* @return whether we have a next smallest number
*/
public boolean hasNext() {
return node != null;
}
public static void main(String[] args) {
Codec codec = new Codec();
TreeNode root;
root = codec.deserialize("[7,3,15,null,null,9,20]");
BSTIterator2 bstIterator = new BSTIterator2(root);
while (bstIterator.hasNext()) {
System.out.println(bstIterator.next());
}
}
}
/**
* 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();
*/