思路:
用一个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;
};