Tutorialspoint
Problem
Solution
Submissions

Iterator for a Binary Search Tree

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 12

Write a C# program to implement an iterator for a binary search tree (BST) with the following operations: 1. BSTIterator(TreeNode root): Initialize an iterator with the root of a BST. 2. bool HasNext(): Return true if there is a next element in the iteration. 3. int Next(): Return the next smallest element in the BST. The iterator should follow the in-order traversal of the BST (left-root-right).

Example 1
  • Input: root = [7, 3, 15, null, null, 9, 20]
  • Operations:
    • bSTIterator = new BSTIterator(root);
    • bSTIterator.Next(); // return 3
    • bSTIterator.Next(); // return 7
    • bSTIterator.HasNext(); // return true
    • bSTIterator.Next(); // return 9
    • bSTIterator.Next(); // return 15
    • bSTIterator.Next(); // return 20
    • bSTIterator.HasNext(); // return false
Example 2
  • Input: root = [1, null, 3, null, null, 2, null]
  • Operations:
    • bSTIterator = new BSTIterator(root);
    • bSTIterator.HasNext(); // return true
    • bSTIterator.Next(); // return 1
    • bSTIterator.Next(); // return 2
    • bSTIterator.Next(); // return 3
    • bSTIterator.HasNext(); // return false
Constraints
  • The number of nodes in the tree is in the range [1, 10^5]
  • 0 ≤ Node.val ≤ 10^6
  • At most 10^5 calls will be made to HasNext and Next
  • Time Complexity: O(1) average time per operation
  • Space Complexity: O(h) where h is the height of the tree
TreeStackGoldman SachsD. E. Shaw
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a stack to keep track of nodes
  • Initialize the stack by pushing all leftmost nodes
  • To get the next smallest element, pop the top of the stack
  • After popping a node, push all leftmost nodes of its right child
  • The HasNext method checks if the stack is empty

Steps to solve by this approach:

 Step 1: Create a stack to store the nodes for in-order traversal.

 Step 2: Implement a helper method (PushAllLeft) to push all leftmost nodes of a subtree onto the stack.
 Step 3: In the constructor, initialize the stack and push all leftmost nodes of the root.
 Step 4: For the Next() method, pop the top node from the stack.
 Step 5: If the popped node has a right child, push all leftmost nodes of the right child onto the stack.
 Step 6: Return the value of the popped node.
 Step 7: For the HasNext() method, simply check if the stack has any nodes left.

Submitted Code :