【Binary Search Tree Iterator 】cpp
2015-07-14 19:25
429 查看
题目:
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling
Note:
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
代码:
tips:
这个题目的核心就是在于中序遍历 把BST转化成vector,这样可以实现题目的要求。
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.
代码:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class BSTIterator { private: vector<TreeNode*> list; int index; public: BSTIterator(TreeNode *root) { BSTIterator::treeToList(root, this->list); this->index = 0; } static void treeToList(TreeNode* root, vector<TreeNode*>& ret) { if ( !root ) return; BSTIterator::treeToList(root->left, ret); ret.push_back(root); BSTIterator::treeToList(root->right, ret); } /** @return whether we have a next smallest number */ bool hasNext() { return index < this->list.size(); } /** @return the next smallest number */ int next() { return list[index++]->val; } }; /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
tips:
这个题目的核心就是在于中序遍历 把BST转化成vector,这样可以实现题目的要求。
相关文章推荐
- 『Luogu OJ』『C++』Level 1-1
- 重载赋值运算符(c/c++)
- c++11 右值引用与转移语义
- C++面试题四
- C++ 内存分配(new,operator new)详解
- C++生成和使用库文件
- 【Binary Tree Right Side View 】cpp
- C++中placement new操作符(经典)
- c++实现设计模式之适配器模式
- C语言的命名规范
- C/C++程序设计01(内存分配与管理,内存泄露处理)
- C++的运算符重载
- 你所不知道的C和C++运行库
- C++编译器与链接器工作原理
- C++ 语言的 15 个晦涩特性
- C语言运算符优先级 详细列表
- C++运算符优先级
- C++ socket与Flex as3通信的沙盒问题解决
- C++中的操作符重载
- c++函数返回引用