LeetCode---Binary Search Tree Iterator ---C++
2015-09-08 16:30
411 查看
问题描述:
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.
对BST,实现一个迭代器。
思路:对于BST,其中序遍历为排序的。中序遍历的非递归方法,就用到了一个栈。所以该题的思路就是用一个栈来实现。因此BST的迭代器类,有一个私有的stack,在构造函数中把BST中最左边的节点入栈。然后hasnext()函数返回true当栈中还有元素时。next,出栈,返回值为该节点的val,然后判断是否有右节点,若有,则把该节点及其所有左节点入栈。
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.
对BST,实现一个迭代器。
思路:对于BST,其中序遍历为排序的。中序遍历的非递归方法,就用到了一个栈。所以该题的思路就是用一个栈来实现。因此BST的迭代器类,有一个私有的stack,在构造函数中把BST中最左边的节点入栈。然后hasnext()函数返回true当栈中还有元素时。next,出栈,返回值为该节点的val,然后判断是否有右节点,若有,则把该节点及其所有左节点入栈。
/** * 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 != NULL ) { S.push(root); root = root->left; } } /** @return whether we have a next smallest number */ bool hasNext() { if(S.size() > 0) return true; return false; } /** @return the next smallest number */ int next() { int result = 0; if(!S.empty()) { TreeNode* node = S.top(); result = node->val; S.pop(); node = node->right; while(node != NULL) { S.push(node); node = node->left; } } return result; } private: std::stack<TreeNode*> S; }; /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
相关文章推荐
- 黑马程序员-C语言回顾-开发概述
- C语言之memset
- C++中类字节对齐
- 【more effective c++读书笔记】【第5章】技术(6)——Proxy classes(代理类)
- 【more effective c++读书笔记】【第5章】技术(6)——Proxy classes(代理类)
- C++读取XML,tinyXml的使用
- [转]标准C++中的string类的用法总结
- 漫谈C指针第十五讲---函数名其实也是指针
- C语言内分配
- C++ STL的查找算法
- Effective C++读书笔记版-条款01,02
- C++中未解之谜
- C语言野指针的产生原因及避免办法
- C/C++函数返回值为指针时(2016美团模拟笔试)
- C语言中int的取值范围是怎么算出来的
- 漫谈C指针第十四讲---一个指针应用实例
- [leetcode]Power of Two C语言
- 了解inline函数(Effective_C++(30))
- 关于PB调用C++的DLL
- Storm安装