思路:二叉树中序遍历的迭代形式。
class BSTIterator {
public:
BSTIterator(TreeNode* root) {
while (root)
{
s.push(root);
root = root->left;
}
}
int next() {
TreeNode* t = s.top();
s.pop();
int ans = t->val;
if (t->right) {
t = t->right;
while (t) {
s.push(t);
t = t->left;
}
}
return ans;
}
bool hasNext() {
return !s.empty();
}
private:
stack<TreeNode*> s;
};