LeetCode 173. Binary Search Tree Iterator
原题链接
中等
作者:
Ccc1Z
,
2020-07-15 20:44:25
,
所有人可见
,
阅读 453
思路:
- 要求二叉搜索树的下一个最小值
- 就是求二叉搜索树的中序遍历的下一个数
- 所以就是求BST的中序遍历
- 这里使用一个栈来实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class BSTIterator {
Stack<TreeNode> stk;
public BSTIterator(TreeNode root) {
stk = new Stack<>();
while(root != null){
stk.push(root);
root = root.left;
}
}
/** @return the next smallest number */
public int next() {
TreeNode cur = stk.pop();
int ans = cur.val;
cur = cur.right;
while(cur != null){
stk.push(cur);
cur = cur.left;
}
return ans;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stk.isEmpty();
}
}
/**
* 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();
*/