/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
stack<TreeNode *> s;
public:
BSTIterator(TreeNode *root) {
TreeNode *cur = root;
while (cur) {
s.push(cur);
cur = cur->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !s.empty();
}
/** @return the next smallest number */
int next() {
if (!hasNext()) return 0;
TreeNode* t = s.top();
int res = t->val;
s.pop();
t = t->right;
while (t) {
s.push(t);
t = t->left;
}
return res;
}
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/Binary Search Tree Iterator
最新推荐文章于 2024-05-04 15:02:13 发布
本文介绍了一种用于遍历二叉搜索树的迭代器实现方法。该迭代器能够按升序返回树中的元素,并提供了 hasNext 和 next 两个主要功能。通过对给定的二叉树节点进行预处理,迭代器可以高效地找到下一个最小值。
817

被折叠的 条评论
为什么被折叠?



