Why can't we just use a queue and in-order traversal?


  • 0
    S

    public class BSTIterator {
    LinkedList<Integer> queue;

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

    }


  • 0
    H

    This would use O(n) space where n is total number of nodes.


Log in to reply
 

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