Solution using Stack.


  • 0
    V
    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    
    public class BSTIterator {
        private Stack<TreeNode> iterator;
        public BSTIterator(TreeNode root) {
            TreeNode node = root;
            iterator = new Stack<TreeNode>();
            while (node != null) {
                iterator.push(node);
                node = node.left;
            }
        }
    
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return !iterator.isEmpty();
        }
    
        /** @return the next smallest number */
        public int next() {
            TreeNode top = iterator.pop();  
            if (top.right != null) {
                TreeNode curr = top.right;
                while (curr != null) {
                    iterator.push(curr);
                    curr = curr.left;
                }
            }    
            return top.val;
        }
    }
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = new BSTIterator(root);
     * while (i.hasNext()) v[f()] = i.next();
     */
    

Log in to reply
 

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