173. Binary Search Tree Iterator
来源:互联网 发布:java io流写入文件 编辑:程序博客网 时间:2024/06/16 20:15
/** * 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) { 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* tmp = stk.top(); int val = tmp->val; stk.pop(); tmp = tmp->right; while(tmp) { stk.push(tmp); tmp = tmp->left; } return val; }private: stack<TreeNode*> stk;};/** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
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.
【思路】暴力的方法是遍历整个树然后将所有元素放入有序的队列中,依次取出,但空间复杂度为O(n)。O(h)的复杂度的解法可通过一个栈来实现:依次将最左边的元素压栈,每次弹出最左下的元素即为最小的元素,同时判断其是否有右子树,若有右子树则继续将其右结点的左边元素依次压栈,循环直到栈为空。
0 0
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator**
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- StringBuilder、StringBuffer和String详解
- bzoj-4551 [Tjoi2016&Heoi2016]树
- mysql 事务级别
- Android入门学习——Retrofit+MVP模式学习
- 硬币排成线
- 173. Binary Search Tree Iterator
- Problem M
- POJ 3254 Corn Fields(状态压缩dp)
- 如何使用php文件测试mongodb是否安装成功
- latex 与 Mathtype使用问题集锦(不断充实中....)
- spark第一个简单示例的源码解读
- 01_JSP 教程
- ssh整合
- Glib学习(3) 双端队列 Double-ended Queues