Simple Java Sol beats 98% 4 ms using Queue


  • 0
    public class BSTIterator {
        Queue<TreeNode> Q;
        public BSTIterator(TreeNode root) {
            Q = new LinkedList();
            helper(root);
        }
        void helper(TreeNode root){
            if(root==null) return;
            helper(root.left);
            Q.add(root);
            helper(root.right);
        }
        public boolean hasNext() {
            return Q.peek()==null?false:true;
        }
    
        public int next() {
            return Q.poll().val;
        }
    }
    

  • 0
    M

    I don't think that you are using a O(h) space, where h is the height of the tree. You are using O(n), where n is the total number of nodes in the tree.


Log in to reply
 

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