Super easy Java solution using a queue. Beat 86%.


  • 0

    public class BSTIterator {

    Queue<Integer> queue = new LinkedList<Integer>();
    
    public void BSTUtil(TreeNode root)
    {
        if(root == null)
            return;
        
        BSTUtil(root.left);
        queue.add(root.val);
        BSTUtil(root.right);
    }
    
    public BSTIterator(TreeNode root) {
        
        BSTUtil(root);
    }
    
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !(queue.isEmpty());
    }
    
    /** @return the next smallest number */
    public int next() {
        return queue.poll();
    }
    

    }


  • 1
    R

    it's not h space.


Log in to reply
 

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