What if you could flip through a huge sorted list one item at a time without losing your place or extra effort?
Why BST Iterator Design in DSA C++?
Imagine you have a large family photo album sorted by year, but you want to look at each photo one by one in order. Without a tool, you'd have to flip pages back and forth manually, which is tiring and confusing.
Manually tracking which photo you saw last is slow and easy to mess up. You might lose your place or repeat photos. It's hard to remember where you are without a clear system.
A BST Iterator acts like a smart bookmark that remembers your place and gives you the next photo in order without flipping back and forth. It makes moving through the album smooth and error-free.
void printInOrder(Node* root) {
if (!root) return;
printInOrder(root->left);
std::cout << root->val << " ";
printInOrder(root->right);
}
// No way to pause and resume easilyclass BSTIterator { std::stack<Node*> nodes; void pushLeft(Node* node) { while (node) { nodes.push(node); node = node->left; } } public: BSTIterator(Node* root) { pushLeft(root); } int next() { Node* top = nodes.top(); nodes.pop(); if (top->right) pushLeft(top->right); return top->val; } bool hasNext() { return !nodes.empty(); } };
It enables smooth, step-by-step access to sorted data without extra memory or confusion.
Like a music playlist that remembers which song played last and plays the next one automatically, a BST Iterator remembers the last visited node and gives the next smallest value on demand.
Manual traversal is slow and error-prone.
BST Iterator remembers position and returns next element efficiently.
It simplifies working with sorted tree data step-by-step.