My solution with Queue


  • -1
    M

    public class BSTIterator {
    Queue<TreeNode> queue;
    // add all the node in queue;
    private void addAllNode(TreeNode root, Queue<TreeNode> queue) {
    if(root == null) {
    return;
    }
    addAllNode(root.left, queue);
    queue.offer(root);
    addAllNode(root.right, queue);
    }
    //@param root;
    public BSTIterator(TreeNode root) {
    queue = new LinkedList<TreeNode>();
    addAllNode(root, queue);
    }

    public boolean hasNext() {
    	return queue.size() !=0;
    }
    
    public int next() {
        TreeNode node = queue.poll();
        int result = node.val;
    	return result;
    }
    

    }
    /**

    • 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.