思路:二叉树的递归中序遍历
/**
* 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 {
vector<int> v;
public:
BSTIterator(TreeNode* root) {
stack<TreeNode*> s;
TreeNode* p=root;
while(p||!s.empty())
{
while(p)
{
s.push(p);
p=p->right;
}
if(!s.empty())
{
p=s.top();
s.pop();
v.push_back(p->val);
p=p->left;
}
}
}
/** @return the next smallest number */
int next() {
int temp=v.back();
v.pop_back();
return temp;
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !v.empty();
}
};