Java stack solution


  • 0
    J

    next() method sometimes will push until the left most leaf. but the average time is O(1). Is it acceptable?

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

Log in to reply
 

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