Simple solution using Priority Queue


  • 0
    R

    Priority Queue, by its implementation as a min-heap, is ideally suited for this task. Here is my accepted code:

    public class BSTIterator {
        
        PriorityQueue<Integer> vals;
        
        public BSTIterator(TreeNode root) {
            this.vals = new PriorityQueue<Integer>();
            inorder(root);
        }
        
        private void inorder(TreeNode node){
            if(node != null){
                inorder(node.left);
                vals.offer(node.val);
                inorder(node.right);
            }
        }
    
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return (vals.size() > 0);
        }
    
        /** @return the next smallest number */
        public int next() {
            return vals.poll();
        }
    }
    

Log in to reply
 

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