标签:
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.
这道题是要求实现一个二叉搜索树的迭代器,该迭代器会使用二叉搜索树的根节点进行初始化,调用next()返回二叉搜索树中下一个最小树。有一个注意点:next()和hasNext()应该满足O(1)的时间复杂度和O(h)的空间复杂度,其中h是二叉搜索树的高度。
下面贴上代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
stack<TreeNode*> s;
BSTIterator(TreeNode *root) {
while(root){
s.push(root);
root=root->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !s.empty();
}
/** @return the next smallest number */
int next() {
TreeNode* tn=s.top();
s.pop();
int ans=tn->val;
if(tn->right){
tn=tn->right;
while(tn){
s.push(tn);
tn=tn->left;
}
}
return ans;
}
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
[LeetCode]Binary Search Tree Iterator
标签:
原文地址:http://blog.csdn.net/kaitankedemao/article/details/43836233