173. Binary Search Tree Iterator
Medium
1309237FavoriteShare
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next()
will return the next smallest number in the BST.
Example:
BSTIterator iterator = new BSTIterator(root); iterator.next(); // return 3 iterator.next(); // return 7 iterator.hasNext(); // return true iterator.next(); // return 9 iterator.hasNext(); // return true iterator.next(); // return 15 iterator.hasNext(); // return true iterator.next(); // return 20 iterator.hasNext(); // return false
class BSTIterator {
private:
int NextMin;
stack<TreeNode*> s;
public:
BSTIterator(TreeNode* root) {
if(root == NULL){return;}
s.push(root);
TreeNode* left = root->left;
while(left){
s.push(left);
NextMin = left->val;
left = left ->left;
}
}
/** @return the next smallest number */
int next() {
if(hasNext()){
TreeNode* tmp = s.top();
s.pop();
NextMin = tmp->val;
TreeNode* tmp1 = tmp->right;
if(tmp1){
s.push(tmp1);
while(tmp1->left != NULL){
s.push(tmp1->left);
tmp1 = tmp1->left;
}
}
return NextMin;
}
return -1;
}
/** @return whether we have a next smallest number */
bool hasNext() {
if(!s.empty()){
return true;
}
return false;
}
};
这道题考察的是二叉搜索树与栈的使用,构造函数里面讲根节点的左节点依次加入到栈中,这样就能保证栈顶永远是最小的元素。注意变量名的命名问题!