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

【Binary Search Tree Iterator 】cpp

2015-07-14 19:25 429 查看
题目:

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

代码:

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
private:
vector<TreeNode*> list;
int index;
public:
BSTIterator(TreeNode *root) {
BSTIterator::treeToList(root, this->list);
this->index = 0;
}

static void treeToList(TreeNode* root, vector<TreeNode*>& ret)
{
if ( !root ) return;
BSTIterator::treeToList(root->left, ret);
ret.push_back(root);
BSTIterator::treeToList(root->right, ret);
}

/** @return whether we have a next smallest number */
bool hasNext() {
return index < this->list.size();
}

/** @return the next smallest number */
int next() {
return list[index++]->val;
}
};

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


tips:

这个题目的核心就是在于中序遍历 把BST转化成vector,这样可以实现题目的要求。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: