AlgoMaster Logo

Binary Search Tree Iterator

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Basic Approach: In-Order Traversal with List

Intuition:

The basic intuition is to leverage the property of a BST where an in-order traversal gives nodes in a non-decreasing order. We can perform an in-order traversal of the tree, store all nodes in a list, and then use this list to ensure constant time access to the next smallest node.

Approach:

  1. Perform an in-order traversal of the BST.
  2. Store the elements in a list as they are visited.
  3. Use an index to track the current element in the list.
  4. next() simply retrieves the element at the current index and then increments it.
  5. hasNext() checks if the current index is less than the list size.

Code:

2. Optimal Approach: Controlled Recursion

Intuition:

The goal is to simulate the in-order traversal using controlled stack-based recursion. The benefit is an iterative approach with a controlled stack of nodes which represents the path from the root to the next smallest node. Thus, it uses less memory than storing all nodes.

Approach:

  1. Use the stack to keep track of the nodes that need to be visited.
  2. Initialize by traversing from the root to the leftmost node, pushing all the nodes on the path to the stack.
  3. hasNext() is simple: check if there are any nodes left in the stack.
  4. For next(), pop the top node from the stack (the current smallest).
  5. If this node has a right child, push all its left descendants onto the stack.

Code: