您的位置:首页 > 编程语言 > Go语言

Binary Search Tree Iterator

2015-03-13 18:16 176 查看
这道题目表述的不太好,容易造成误解,我就误解了2次。。。“next smallest number”其实指的就是树中的最小元素,所以说白了就是每次都返回最小元素即可。

所以一个很直觉的解法就是:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
TreeNode* root;
BSTIterator(TreeNode *root) {
this->root=root;
}

/** @return whether we have a next smallest number */
bool hasNext() {
if(root)
{
return true;
}
else
{
return false;
}
}

/** @return the next smallest number */
int next() {
TreeNode* par=NULL;
TreeNode* tmp=root;
while(tmp->left)
{
par=tmp;
tmp=tmp->left;
}
int res=tmp->val;
if(par==NULL)
{
root=root->right;
}
else
{
par->left=tmp->right;
}
return res;

}
};

/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/

上述解法修改了原来的树,未使用额外存储空间,hasNext复杂度为O(1),但是next复杂度为O(logN),不满足题目要求的O(1)复杂度。

注意到其实本题与树的中序遍历有异曲同工之妙,只不过这里需要“暂存中间状态”,而在非递归的中序遍历中使用了栈,这是天然的“中间状态暂存处”。这样一来,使用了额外O(h)的存储空间,做到了hasNext与next的复杂度均达到了O(1)。注意,next复杂度之所以是O(1)是因为,树中的每个节点恰好只进入一次栈,所以在调用n次next输出全部节点后,总的进栈操作是n,所以平均每次next操作进栈一次,所以是O(1)

改进的解法如下:

/**
* 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*> mstack;
BSTIterator(TreeNode *root) {
while(root)
{
mstack.push(root);
root=root->left;
}
}

/** @return whether we have a next smallest number */
bool hasNext() {
if(mstack.empty())
{
return false;
}
else
{
return true;
}
}

/** @return the next smallest number */
int next() {
TreeNode* tmp=mstack.top();
mstack.pop();
int res=tmp->val;
if(tmp->right)
{
tmp=tmp->right;
while(tmp)
{
mstack.push(tmp);
tmp=tmp->left;
}
}
return res;
}
};

/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm leetcode