Binary Search Tree Iterator
来源:互联网 发布:电影网站源码带采集 编辑:程序博客网 时间:2024/05/01 18:32
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.
一颗BST,它的最小值是哪个点?没错,就是这颗树的最左一个节点。那么它之后的最小节点呢?
就变成了找比当前节点大的最小的那个节点。就是当前节点右子树中最左的那个节点、如果右子树不存在,那么是其父节点
/** * 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 *> s;public: BSTIterator(TreeNode *root) { pushLeft(root); } /** @return whether we have a next smallest number */ bool hasNext() { return !s.empty(); } /** @return the next smallest number */ int next() { TreeNode *cur = s.top(); s.pop(); pushLeft(cur->right); return cur->val; } void pushLeft(TreeNode *root) { while(root!=NULL) { s.push(root); root = root->left; } }};/** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
0 0
- 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
- Openstack镜像和密码
- C# using用法
- busybox自带的tftp服务器
- excel------------打印问题
- error LNK2005: __CrtSetCheckCount already defined in msvcrtd.lib
- Binary Search Tree Iterator
- IOS中scrollsToTop问题小结
- dwr回调函数设置参数
- ORACLE 数据库表结构和数据的导出导入
- C# 过滤sql特殊字符方法集合
- restful webservice简介
- jquery:return false
- 制作python模块安装包
- 一句话系列之XML