Binary Search Tree Iterator
来源:互联网 发布:ios mvvm数据绑定原理 编辑:程序博客网 时间:2024/05/21 10:21
1.问题描述
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.
2解决思路
题目要求在常数的平均时间内访问到当前元素的后继节点.如果当前迭代器所指元素没有右子树,那么它的后继节点将是其父节点,而题目中的节点是不包含指向父节点的指针的,因此使用栈来保存其父节点.
把从根节点到值最小的节点的路径上的所有节点都压在一个栈上面,保证栈顶的元素是当前迭代器所要访问的最小元素,栈顶的下一个元素是其父节点.
初始化时,建立栈,依次将根节点的所有左子节点压到栈上.
执行next()函数时,分两种情况
2.1如果当前节点的右子树为空,则直接将该节点弹除栈,栈顶是其父节点,在这种情况下,父节点就是该节点的后继.
2.2如果当前节点的右子树,不为空,首先弹出该节点,然后需要将右子节点的所有左节点压到栈上,操作与构造时执行一样.
执行hasNext()时即判断栈中元素是否为空
3代码
/** * 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) { successor(root); } /** @return whether we have a next smallest number */ bool hasNext() { return !node_stack.empty(); } /** @return the next smallest number */ int next() { TreeNode* cur=node_stack.top(); node_stack.pop(); if(cur->right){ successor(cur->right); } return node_stack.top()->val; } /**guarantee that cur->right!=NULL **/ void successor(TreeNode* root){ while(root){ node_stack.push(root); root=root->left; } }private: stack<TreeNode*> node_stack;};/** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
4总结
常用的常数时间访问元素的数据结构,最大堆访问最大的元素,最小堆访问最小的元素.
hash table 按照key访问元素.栈中访问栈顶元素等,…恩暂时想到这么多.
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- AssetBundle的初步使用
- Git4-使用规范流程
- mysql5.7解压版安装配置中遇到的一些问题
- 关于scikit-learn的multiclass下的分类理解
- Git5-.gitignore的使用
- Binary Search Tree Iterator
- mysql数据库移机(备份)的最安全最简洁的方法
- C++第四次实验报告
- 四月九
- 【Python学习】python爬虫Google翻译的实现
- 1006. 换个格式输出整数 (15)
- Unity3D 多个网格模型合并 插件
- 简单的递推练习
- 关于getClass().getResourceAsStream(path)跨项目取文件资源返回值为null的报错