您的位置:首页 > 编程语言 > C语言/C++

leetcode_c++:栈:Binary Search Tree Iterator(173)

2016-07-22 16:42 471 查看
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.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

class BSTIterator {
private:
queue<int> in_res;
void inorder(TreeNode* root){
if(root!=NULL){
inorder(root->left);
in_res.push(root->val);
inorder(root->right);
}
}

public:
BSTIterator(TreeNode *root) {
while(!in_res.empty())
in_res.pop();
inorder(root);

}

/** @return whether we have a next smallest number */
bool hasNext() {
return in_res.size()!=0;

}

/** @return the next smallest number */
int next() {

int front=in_res.front();
in_res.pop();
return front;
}
};


vector模拟

class BSTIterator {
private:
vector<int> v;
int pos;
//travse the tree in-order and convert it to the array
public:
BSTIterator(TreeNode *root) {
pos=0;
vector<TreeNode*>  stack;
while(stack.size()>0||root!=NULL){
if(root){
stack.push_back(root);
root=root->left;
}else{
root = stack.back();
stack.pop_back();
v.push_back(root->val);
root=root->right;
}
}

}

/** @return whether we have a next smallest number */
bool hasNext() {
return pos<v.size();

}

/** @return the next smallest number */
int next() {

return v[pos++];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: