思路:
用一个stack记录左节点. 上来先把整个树的最左一流节点push到栈中. 如果要看是否有下一个节点, 那么就看栈是否空, 如果要得到下一个节点的数值, 就把栈顶的元素返回出去, 并且把栈顶的树的右节点的左边一流节点push到栈中. 这样其实空间是O(h)的, next()函数的最坏时间复杂度也是O(h), 但平均时间开销是O(1), 符合题目要求.
class BSTIterator {
public:
BSTIterator(TreeNode *root) {
TreeNode* temp = root;
while (temp) {
s.push(temp);
temp = temp->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return ! s.empty();
}
/** @return the next smallest number */
int next() {
TreeNode* cur = s.top();
s.pop();
TreeNode* temp = cur->right;
while (temp) {
s.push(temp);
temp = temp->left;
}
return cur->val;
}
private:
stack<TreeNode*> s;
};
本文介绍了一种使用栈实现二叉搜索树迭代器的方法,该方法能够在平均时间开销为O(1)的情况下实现对二叉搜索树的中序遍历。通过预先将根节点及其所有左子节点压入栈中,每次调用next()函数时都能快速返回最小的未访问节点,并更新栈以准备返回下一个节点。
1239

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



