Magicsheet logo

Binary Search Tree Iterator II

Medium
25%
Updated 8/1/2025

Binary Search Tree Iterator II

What is this problem about?

The "Binary Search Tree Iterator II interview question" is an advanced version of the BST iterator. In addition to next() and hasNext(), you must also support prev() and hasPrev(). This means you need to be able to move both forward and backward through the sorted sequence of the tree's values.

Why is this asked in interviews?

Meta asks the "Binary Search Tree Iterator II coding problem" to evaluate a candidate's ability to cache and manage history. Since a standard iterator only moves forward, you need a way to "remember" where you've been without losing the efficiency of the stack-based traversal. It tests "Design interview pattern" and "List" management.

Algorithmic pattern used

This problem combines Stack-based Traversal with a Dynamic List/Cache.

  1. Standard Iterator: Use the same stack logic as the basic iterator to find new elements.
  2. History List: As you discover elements with next(), store them in a list.
  3. Pointer Logic: Maintain a pointer index in your history list.
    • next(): If the pointer is not at the end of the list, move the pointer and return the value. If it is at the end, use the stack to find the next element, add it to the list, and then move the pointer.
    • prev(): Simply move the pointer back and return the value from the list.

Example explanation

BST: [3, 7, 9, 15, 20]

  1. next(): Finds 3. History: [3], Pointer: 0.
  2. next(): Finds 7. History: [3, 7], Pointer: 1.
  3. prev(): Moves pointer to 0. Returns 3.
  4. next(): Moves pointer back to 1. Returns 7.
  5. next(): Finds 9 via stack. History: [3, 7, 9], Pointer: 2.

Common mistakes candidates make

  • Full traversal at start: Like the basic version, avoid doing a full in-order traversal up front. You should only traverse as much as needed.
  • Pointer sync: Getting the pointer index wrong when switching between next() and prev() calls.
  • Complexity: Over-complicating the logic by trying to manage two stacks (one for next, one for prev) when a simple list + pointer is much cleaner.

Interview preparation tip

When adding "undo" or "previous" functionality to a data structure, a combination of the original logic and a history cache is the standard design pattern. This mirrors how many real-world "Undo" features are implemented.

Similar Questions