实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。

调用 next() 将返回二叉搜索树中的下一个最小的数。

注意: next() 和hasNext() 操作的时间复杂度是O(1),并使用 O(h) 内存,其中 h 是树的高度。

其实就是二叉树的中序遍历,手动模拟函数递归调用时候的出入栈即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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() {
TreeNode* cur = s.top();
s.pop();
TreeNode* tmp = cur->right;
while (tmp) {
s.push(tmp);
tmp = tmp->left;
}
return cur->val;
}
};