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

LeetCode-Binary Search Tree Iterator-解题报告

2015-07-03 15:43 423 查看
原题链接https://leetcode.com/problems/binary-search-tree-iterator/

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, whereh is the height of the tree. 

嗯,  开始没注意要O(h)的额外空间要求。

可以这样,在构造函数中我定义了一个双端队列,应为要用到在队列前插入和删除的操作。

首先我们在构造函数中先压入根节点。

在hasnext中  我们将节点的一直向左的点压入按照层次的顺序压入队列中,为什么?  最小的一定是最左边的 如果存在的话。为了防止相同节点的入队两次,入队一次便把left置为NULL

在next中,保存队首元素,并出队,如果队首元素的右节点存在,则压入队首。

队列中的元素个数 最多为 数的高度 即额外空间为O(h)

next() O(1)

hasnext() 因为一直向左 O(h)

实在没想到O(1)的hasnext(), 

/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
BSTIterator(TreeNode *root) {
if (root != NULL)
val.push_front(root);
}
/** @return whether we have a next smallest number */
bool hasNext() {
if (val.empty())return false;
TreeNode* Node = val.front();
left(Node->left);
Node->left = NULL;
return val.size();
}

/** @return the next smallest number */
int next() {
TreeNode* Node = val.front();
val.pop_front();
if (Node->right != NULL)val.push_front(Node->right);
return Node->val;
}
private:
void left(TreeNode* root)
{
if (root == NULL)return;
val.push_front(root);
left(root->left);
root->left = NULL;
}
deque<TreeNode*>val;
};

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