Simple JAVA solution using queue


  • 0
    S

    public class BSTIterator {

    ArrayDeque<Integer> list;
    
    public BSTIterator(TreeNode root) {
        list = new ArrayDeque<Integer>();
        inorderTraverse(root);
    }
    
    void inorderTraverse(TreeNode root)
    {
        if(root == null)
            return;
        inorderTraverse(root.left);
        list.addLast(root.val);
        inorderTraverse(root.right);
    }
    
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        if(list.isEmpty())
            return false;
        else
            return true;
    }
    
    /** @return the next smallest number */
    public int next() {
        return list.removeFirst();
    }
    

    }


Log in to reply
 

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