Short java iterative solution


  • 2
    B
    Stack<TreeNode> s = new Stack<TreeNode>();
    public BSTIterator(TreeNode root) {
        helper(root);
    }
    
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !s.isEmpty();
    }
    
    /** @return the next smallest number */
    public int next() {
        TreeNode cur = s.pop();
        helper(cur.right);
        return cur.val;
    }
    public void helper(TreeNode t) {
        while (t != null) {
            s.push(t);
            t = t.left;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.