Skip to content

Commit 324948c

Browse files
author
applewjg
committed
update
Change-Id: Ia2dee999b1df05f6a6f36a10cf2beeaf1f65889f
1 parent 04022c7 commit 324948c

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

BinarySearchTreeIterator.java

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ Calling next() will return the next smallest number in the BST.
2323
* }
2424
*/
2525

26-
public class BSTIterator {
26+
public class BSTIterator_1 {
2727

2828
public BSTIterator(TreeNode root) {
2929
stk = new Stack<TreeNode>();
@@ -53,6 +53,46 @@ public int next() {
5353
private TreeNode node;
5454
}
5555

56+
57+
public class BSTIterator_2 {
58+
59+
public BSTIterator(TreeNode root) {
60+
node = root;
61+
}
62+
63+
/** @return whether we have a next smallest number */
64+
public boolean hasNext() {
65+
return node != null;
66+
}
67+
68+
/** @return the next smallest number */
69+
public int next() {
70+
if (node == null) return 0;
71+
int res = 0;
72+
while (node != null) {
73+
if (node.left == null) {
74+
res = node.val;
75+
node = node.right;
76+
return res;
77+
}
78+
TreeNode pre = node.left;
79+
while (pre.right != null && pre.right != node)
80+
pre = pre.right;
81+
if (pre.right == null) {
82+
pre.right = node;
83+
node = node.left;
84+
} else {
85+
res = node.val;
86+
node = node.right;
87+
pre.right = null;
88+
return res;
89+
}
90+
}
91+
return res;
92+
}
93+
private TreeNode node;
94+
}
95+
5696
/**
5797
* Your BSTIterator will be called like this:
5898
* BSTIterator i = new BSTIterator(root);

0 commit comments

Comments
 (0)