leetcode 173. Binary Search Tree Iterator

 

class BSTIterator {
    private Stack<TreeNode> stack;
    public BSTIterator(TreeNode root) {
        stack = new Stack<>();
        while(root != null){
            stack.push(root);
            root = root.left;
        }
    }
    
    /** @return the next smallest number */
    public int next() {
        TreeNode cur = stack.pop();
        TreeNode tmp = cur;
        if(tmp != null){
            tmp = tmp.right;
            while(tmp != null){
                stack.push(tmp);
                tmp = tmp.left;
            }
        }
        
        return cur.val;
    }
    
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        
        return !stack.isEmpty();
    }
}

 

相关文章:

  • 2022-12-23
  • 2021-11-01
  • 2022-02-12
  • 2021-10-08
  • 2021-07-06
  • 2022-02-04
猜你喜欢
  • 2021-04-06
  • 2021-08-12
  • 2021-07-08
  • 2021-07-18
  • 2021-10-15
  • 2022-12-23
  • 2022-01-10
相关资源
相似解决方案