class BSTIterator {
public:
BSTIterator(TreeNode *root) {
while (root) {
lst.push_back(root);
TreeNode *tmp = root->left;
root = root->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
if (!lst.empty())
return true;
else
return false;
}
/** @return the next smallest number */
int next() {
int res = lst.back()->val;
TreeNode *tmp = lst.back();
lst.pop_back();
tmp = tmp->right;
while (tmp) {
lst.push_back(tmp);
tmp = tmp->left;
}
return res;
}
list<TreeNode *> lst;
};
Binary Search Tree Iterator: O(1)时间复杂度,O(h)空间复杂度
最新推荐文章于 2022-03-09 15:31:27 发布