class BSTIterator {
public:
vector<TreeNode *> box;
BSTIterator(TreeNode *root) {
//把二叉树最左边的一列全部加入box
while (root != NULL) {
box.push_back(root);
root = root->left;
}
}
int next() {
auto now = box.back();
box.pop_back(); //box最后一个元素即为ans
//下面5行把所now结点的右子树的最左边一列加入box
auto temp = now->right;
while (temp != NULL) {
box.push_back(temp);
temp = temp->left;
}
return now->val;
}
bool hasNext() { return !box.empty(); }
};
173. 二叉搜索树迭代器
最新推荐文章于 2024-07-23 17:36:37 发布