LeetCode - Binary Search Tree Iterator
2015-07-14 13:41
288 查看
Binary Search Tree Iterator
Total Accepted: 20470 TotalSubmissions: 69577My Submissions
Question
Solution
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.
s
class BSTIterator {
public:
BSTIterator(TreeNode *root) {
while(root){
stk.push(root);
root = root->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !stk.empty();
}
/** @return the next smallest number */
int next() {
TreeNode* now = stk.top();
int ret = now->val;
stk.pop();
if(now->right){
now = now->right;
while(now){
stk.push(now);
now = now->left;
}
}
return ret;
}
private:
stack<TreeNode*> stk;
};
相关文章推荐
- AVL树-自平衡二叉查找树(Java实现)
- C语言二叉树的非递归遍历实例分析
- 浅析iterator与指针的区别
- C++非递归队列实现二叉树的广度优先遍历
- C#使用前序遍历、中序遍历和后序遍历打印二叉树的方法
- java使用iterator遍历指定目录示例分享
- Java设计模式之Iterator模式介绍
- C++非递归建立二叉树实例
- C语言实现找出二叉树中某个值的所有路径的方法
- C++实现二叉树遍历序列的求解方法
- C语言实现二叉树遍历的迭代算法
- C++实现二叉树非递归遍历方法实例总结
- C++二叉树结构的建立与基本操作
- 深入遍历二叉树的各种操作详解(非递归遍历)
- JavaScript数据结构和算法之二叉树详解
- 使用Enumeration和Iterator遍历集合类详解
- java使用归并删除法删除二叉树中节点的方法
- python数据结构之二叉树的建立实例
- python数据结构树和二叉树简介
- python数据结构之二叉树的统计与转换实例