解题思路:
使用中序遍历,将二叉搜索树的所有节点值依次push进队列中。每调用依次next函数,即返回队首元素,并pop。hasNext函数只需判断队列是否为空即可。
/**
* 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:
queue<int> q;
BSTIterator(TreeNode* root) {
//递归中序遍历
inorder(root, q);
}
//递归中序遍历函数
void inorder(TreeNode* root, queue<int>& q){
if(root == NULL) return;
inorder(root->left, q);
q.push(root->val);
inorder(root->right, q);
}
/** @return the next smallest number */
int next() {
int tmp = q.front();
q.pop();
return tmp;
}
/** @return whether we have a next smallest number */
bool hasNext() {
if(q.empty()) return false;
else return true;
}
};
/**
* 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();
*/