题目:https://leetcode-cn.com/problems/binary-search-tree-iterator/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
/*
*实现一个二叉搜索树迭代器。你将使用二叉搜索树的
*根节点初始化迭代器。调用 next() 将返回二叉搜索
*树中的下一个最小的数。
*/
stackst;
BSTIterator(TreeNode* root) {
while(root){
st.push(root);
root=root->left;
}
}
int next() {
TreeNode* p=st.top();
st.pop();
int ans=p->val;
p=p->right;
while(p){
st.push(p);
p=p->left;
}
return ans;
}
bool hasNext() {
return !st.empty();
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/