LeetCode 1586: Binary Search Tree Iterator II Solution

Master LeetCode problem 1586 (Binary Search Tree Iterator II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1586. Binary Search Tree Iterator II

Problem Explanation

Explanation:

To implement the Binary Search Tree Iterator II, we can use the same approach as the Binary Search Tree Iterator but with the additional functionalities of hasPrev() and prev() methods.

  1. Create a stack to store the nodes in the path from the root to the current node.
  2. In the constructor, initialize the stack with nodes up to the leftmost node.
  3. The hasNext() method returns true if there are more nodes to visit (i.e., the stack is not empty).
  4. The next() method returns the next smallest node and updates the stack accordingly.
  5. The hasPrev() method returns true if there are previous nodes to visit (i.e., the stack is not empty).
  6. The prev() method returns the previous largest node and updates the stack accordingly.

:

Solution Code

class BSTIterator {
    Stack<TreeNode> stack;

    public BSTIterator(TreeNode root) {
        stack = new Stack<>();
        while (root != null) {
            stack.push(root);
            root = root.left;
        }
    }

    public boolean hasNext() {
        return !stack.isEmpty();
    }

    public int next() {
        TreeNode node = stack.pop();
        int result = node.val;
        node = node.right;
        while (node != null) {
            stack.push(node);
            node = node.left;
        }
        return result;
    }

    public boolean hasPrev() {
        return !stack.isEmpty();
    }

    public int prev() {
        TreeNode node = stack.pop();
        int result = node.val;
        node = node.left;
        while (node != null) {
            stack.push(node);
            node = node.right;
        }
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1586 (Binary Search Tree Iterator II)?

This page provides optimized solutions for LeetCode problem 1586 (Binary Search Tree Iterator II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1586 (Binary Search Tree Iterator II)?

The time complexity for LeetCode 1586 (Binary Search Tree Iterator II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1586 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1586 in Java, C++, or Python.

Back to LeetCode Solutions