Binary Search Tree Iterator
https://leetcode.com/problems/binary-search-tree-iterator/description/
Thoughts
Code
class BSTIterator {
public:
stack<TreeNode*> s;
int c = 0;
void push_left(TreeNode *cur) {
while (cur != nullptr) {
s.push(cur);
cur = cur->left;
}
}
BSTIterator(TreeNode* root) {
push_left(root);
}
/** @return the next smallest number */
int next() {
const auto t = s.top();
s.pop();
push_left(t->right);
return t->val;
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !s.empty();
}
};Analysis
Last updated