solution using queue, 5ms

  • 0

    public class BSTIterator {
    Queue<Integer> q;
    public BSTIterator(TreeNode root) {
    q = new LinkedList<>();
    helper(root, q);
    private void helper(TreeNode node, Queue<Integer> q) {
    if (node==null) return;
    helper(node.left, q);
    helper(node.right, q);

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !q.isEmpty();
    /** @return the next smallest number */
    public int next() {
        return q.poll();


  • 0

    it should limited O(h) memory, but your solution was O(n)

Log in to reply

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