Binary Search Tree Iterator —— Leetcode
2015-09-03 23:09
489 查看
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling
Note:
run in average O(1) time and uses O(h) memory, where h is the height of the tree.
设计一个迭代器,关键在于O(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:
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* node = s.top();
s.pop();
if(node->right) {
TreeNode* rightNode = node->right;
s.push(rightNode);
while(rightNode->left) {
s.push(rightNode->left);
rightNode = rightNode->left;
}
}
return node->val;
}
private:
stack<TreeNode*> s;
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
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.
设计一个迭代器,关键在于O(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:
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* node = s.top();
s.pop();
if(node->right) {
TreeNode* rightNode = node->right;
s.push(rightNode);
while(rightNode->left) {
s.push(rightNode->left);
rightNode = rightNode->left;
}
}
return node->val;
}
private:
stack<TreeNode*> s;
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
相关文章推荐
- 精品软件 推荐 电子书转换器 EPUB to PDF Converter
- HDU5000-Clone-AsiaRegionalAnshanOnline2014(01背包问题)
- 2015.09.03 Java设计模式
- openwrt编译error: ext4_allocate_best_fit_partial: failed to allocate 13 blocks, out of space?
- HDU1027(Ignatius and the Princess II)
- 天津市人民优步Uber司机奖励政策(8.31-9.6)
- JavaEE学习之类加载器
- Android dagger2使用
- hdu2147
- [LeetCode] Invert Binary Tree
- easyUI 笔记
- 继承ActionSupport类及Result结果集介绍
- HDU 3966 树链剖分学习
- IOS开发UI—UI控件概览
- 长沙Uber司机奖励政策(8月24日到8月30日)
- Java
- hdu2188(巴什博弈)
- UVA 12929 - Aerial Tramway(dp)
- NYOJ 118 修路方案 (次小生成树--prime)
- 【手势识别-论文学习】 Hands Deep in Deep Learning for Hand Pose Estimation