标签:leetcode tree stack bst 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, where h is the height of the tree.
参考:https://oj.leetcode.com/discuss/20001/my-solutions-in-3-languages-with-stack
解题思路:用一个stack保存从根节点开始的所有左孩子,每次调用next()就从stack里面pop一个元素,并将以这个节点的右孩子为根节点的子树重复同样的过程。
这个算法满足O(h)的空间复杂度,hasNext()的时间复杂度满足O(1),尽管next()的时间复杂度为O(h),但是这个算法的处理过程仍然值得学习。
C++代码实现如下:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
private:
stack<TreeNode *> nodeStack;
void pushAll(TreeNode *root) {
for (TreeNode *node = root; node != nullptr; node = node->left) {
nodeStack.push(node);
}
}
public:
BSTIterator(TreeNode *root) {
pushAll(root);
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !nodeStack.empty();
}
/** @return the next smallest number */
int next() {
TreeNode *node = nodeStack.top();
nodeStack.pop();
pushAll(node->right);
return node->val;
}
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
该算法的时间性能表现如下:
LeetCode[Tree]: Binary Search Tree Iterator
标签:leetcode tree stack bst iterator
原文地址:http://blog.csdn.net/chfe007/article/details/44027503