My solution that beats 88% using queue


  • 0
    T

    I think it is very easy to understand, just use inorder traversal and store the treenode into queue.

    public class BSTIterator {
    private Queue<TreeNode> queue;

    public BSTIterator(TreeNode root) {
        queue = new LinkedList<>();
        inorderTraversal(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().val;   
    }
    
    private void inorderTraversal(TreeNode root){
        if( root == null ) return;
        
        inorderTraversal(root.left);
        queue.add(root);
        inorderTraversal(root.right);
    }
    

    }


Log in to reply
 

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