Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions solution/0173.Binary Search Tree Iterator/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
public class Solution {

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/

class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}

class BSTIterator {

Stack<TreeNode> stack = new Stack<>();

public BSTIterator(TreeNode root) {
while (root!=null){
stack.add(root);
root=root.left;
}
}

/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}

/** @return the next smallest number */
public int next() {
TreeNode current = stack.pop();
TreeNode res = current;
current =current.right;
while (current!=null){
stack.push(current);
current = current.left;
}
return res.val;
}
}

/**
* 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();
*/

}