Approach
Stack-based processing
For Binary Search Tree Iterator II, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.
- Define what every stack entry represents.
- Pop entries once the current item resolves or invalidates them.
- Push the current item with only the information later steps need.
Code notes
- 41 lines of C++ from the credited upstream file 1586.cpp.
- The implementation keeps its working state in language-native values and containers.
- 1 loop block detected.
Complexity
If each item is pushed and popped at most once, the stack work is linear.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class BSTIterator {2 public:3 BSTIterator(TreeNode* root) {4 pushLeftsUntilNull(root);5 }6 7 bool hasNext() {8 return !nexts.empty();9 }10 11 int next() {12 auto [root, fromNext] = nexts.top();13 nexts.pop();14 if (fromNext)15 pushLeftsUntilNull(root->right);16 prevsAndCurr.push(root);17 return root->val;18 }19 20 bool hasPrev() {21 return prevsAndCurr.size() > 1;22 }23 24 int prev() {25 nexts.push({prevsAndCurr.top(), false});26 prevsAndCurr.pop();27 return prevsAndCurr.top()->val;28 }29 30 private:31 stack<TreeNode*> prevsAndCurr;32 stack<pair<TreeNode*, bool>> nexts;33 34 void pushLeftsUntilNull(TreeNode* root) {35 while (root != nullptr) {36 nexts.push({root, true});37 root = root->left;38 }39 }40};41