leetcode_c++:栈:Binary Search Tree Iterator(173)
2016-07-22 16:42
471 查看
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.
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.
class BSTIterator { private: queue<int> in_res; void inorder(TreeNode* root){ if(root!=NULL){ inorder(root->left); in_res.push(root->val); inorder(root->right); } } public: BSTIterator(TreeNode *root) { while(!in_res.empty()) in_res.pop(); inorder(root); } /** @return whether we have a next smallest number */ bool hasNext() { return in_res.size()!=0; } /** @return the next smallest number */ int next() { int front=in_res.front(); in_res.pop(); return front; } };
vector模拟
class BSTIterator { private: vector<int> v; int pos; //travse the tree in-order and convert it to the array public: BSTIterator(TreeNode *root) { pos=0; vector<TreeNode*> stack; while(stack.size()>0||root!=NULL){ if(root){ stack.push_back(root); root=root->left; }else{ root = stack.back(); stack.pop_back(); v.push_back(root->val); root=root->right; } } } /** @return whether we have a next smallest number */ bool hasNext() { return pos<v.size(); } /** @return the next smallest number */ int next() { return v[pos++]; } };
相关文章推荐
- C++对象内存分配
- 鞍点-week7-C语言习题集
- 多项式加法-week7-C语言习题集
- 临时起异,要进入C++领域耍一个程序
- Windows c++剪切板操作
- 完数-week6-C语言习题集
- 分解质因数-week6-C语言习题集
- VTK/VTK6 迁移/“工厂化”需要的定义
- 高精度小数-week5-C语言习题集
- 念整数-week4-C语言习题集
- 素数和-week4-C语言习题集
- leetcode_c++:栈:Min Stack(155)
- 数字特征值-week3-C语言习题集
- 1088. Rational Arithmetic (20)
- 奇偶个数-week3-C语言习题集
- C语言读取文件中文本模式和二进制模式的区别
- 括号匹配
- C语言回调(函数指针)
- HDU 5573 Binary Tree (二进制,位运算)
- Protocol Buffer C++实践