地里新农-请到考试中心学习规则
- 积分
- 0
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-11-22
- 最后登录
- 1970-1-1
|
我用c++实现了一个,大家看看有么有bug吧。。- #include <iostream>
- #include <stack>
- using namespace std;
- struct Tree{
- int val;
- Tree *left, *right;
- Tree(int mval):val(mval), left(NULL), right(NULL){}
- };
- class TreeIterator{
- public:
- TreeIterator(Tree *root){
- flag = true;
- if(root == NULL){
- cur = NULL;
- cout<<"invalid root point"<<endl;
- }else{
- while(root){
- st.push(root);
- root = root->left;
- }
- cur = st.top();
- }
- }
- int value(){
- if(cur == NULL){
- cout<<"invalid operation"<<endl;
- return -1;
- }else{
- cout<<cur->val<<endl;
- return cur->val;
- }
- }
- void next(){
- if(cur == NULL){
- cout<<"No next point"<<endl;
- return;
- }else{
- if(cur->right){
- st.pop();
- cur = cur->right;
- st.push(cur);
- while(cur->left){
- cur = cur->left;
- st.push(cur);
- }
- }else{
- st.pop();
- cur = st.empty()?NULL:st.top();
- }
- }
- }
- bool hasNext(){
- return cur != NULL;
- }
- private:
- stack<Tree* > st;
- Tree* cur;
- bool flag;
- };
- int main(){
- Tree *t1 = new Tree(1);
- Tree *t2 = new Tree(2);
- Tree *t3 = new Tree(3);
- Tree *t4 = new Tree(4);
- Tree *t5 = new Tree(5);
- Tree *t6 = new Tree(6);
- Tree *t7 = new Tree(7);
- t1->left = t2, t1->right = t3;
- t2->left = t4, t2->right = t5;
- t3->left = t6, t3->right = t7;
- TreeIterator tit(t1);
- while(tit.hasNext()){
- tit.value();
- tit.next();
- }
- }
- /*
- 1
- /\
- 2 3
- /\ /\
- 4 56 7
- */
复制代码 |
|