Java Solution using Queue


  • 1
    D
    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    
    public class BSTIterator {
    
        private Queue<TreeNode> queue;
        private void dfs(TreeNode root,Queue<TreeNode> queue){
            if(root == null){
                return;
            }
            dfs(root.left,queue);
            queue.add(root);
            dfs(root.right,queue);
            
        }
        
        public BSTIterator(TreeNode root) {
            queue = new LinkedList<TreeNode>();
            dfs(root,queue);
        }
        
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return !queue.isEmpty();
        }
    
        /** @return the next smallest number */
        public int next() {
            TreeNode node = queue.poll();
            return node.val;
        }
    }
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = new BSTIterator(root);
     * while (i.hasNext()) v[f()] = i.next();
     */
    

Log in to reply
 

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