Skip to content

Commit 8cbbc26

Browse files
authored
Update Binary Search Tree Iterator.java
1 parent 12c415e commit 8cbbc26

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

Medium/Binary Search Tree Iterator.java

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,27 +14,29 @@
1414
* }
1515
*/
1616
class BSTIterator {
17-
Stack<TreeNode> stack;
17+
18+
private Stack<TreeNode> stack;
19+
1820
public BSTIterator(TreeNode root) {
19-
stack = new Stack<>();
20-
while (root != null) {
21-
stack.push(root);
22-
root = root.left;
23-
}
21+
this.stack = new Stack<>();
22+
updateStack(root);
2423
}
2524

2625
public int next() {
27-
TreeNode node = stack.pop();
28-
TreeNode rightNode = node.right;
29-
while (rightNode != null) {
30-
stack.push(rightNode);
31-
rightNode = rightNode.left;
32-
}
26+
TreeNode node = this.stack.pop();
27+
updateStack(node.right);
3328
return node.val;
3429
}
3530

3631
public boolean hasNext() {
37-
return !stack.isEmpty();
32+
return !this.stack.isEmpty();
33+
}
34+
35+
private void updateStack(TreeNode node) {
36+
while (node != null) {
37+
this.stack.push(node);
38+
node = node.left;
39+
}
3840
}
3941
}
4042

0 commit comments

Comments
 (0)