BST Iterator Design
📖 Scenario: Imagine you have a large collection of numbers stored in a Binary Search Tree (BST). You want to look at these numbers one by one in ascending order, like flipping through pages of a book. To do this efficiently, you will build a special tool called a BST Iterator that helps you see the next smallest number each time you ask for it.
🎯 Goal: You will create a BSTIterator class in TypeScript that lets you move through the BST in order. It will have two main actions: next() to get the next smallest number, and hasNext() to check if there are more numbers to see.
📋 What You'll Learn
Create a
TreeNode class to represent nodes in the BST with val, left, and right properties.Create a
BSTIterator class with a constructor that takes the root of the BST.Implement a private stack inside
BSTIterator to help with in-order traversal.Implement
hasNext() method to check if there are more nodes to visit.Implement
next() method to return the next smallest value in the BST.💡 Why This Matters
🌍 Real World
BST iterators are useful in databases and search engines where you need to access sorted data efficiently without loading everything into memory.
💼 Career
Understanding BST iterators helps in roles involving data structure optimization, algorithm design, and backend development where efficient data traversal is critical.
Progress0 / 4 steps