用递归做的前序中序后序遍历

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<numeric>
using namespace std;

class node{
public:
    int val;
    node* left;
    node* right;
    node():val(0),left(NULL),right(NULL){}
};

node* createTree()
{
    node* head = new node[14];
    for(int i = 0;i<10;i++)
    {
        head[i].val = i;
        if(2*i+1 < 10)
        head[i].left = head + 2*i + 1;
        if(2*i+2 < 10)
        head[i].right = head + 2*i + 2;
    }
    return head;
}

void searchfirst(node* head)
{
    if(NULL == head) return;
    else{
    cout<<head->val<<" ";
    searchfirst(head->left);
    searchfirst(head->right);
    }
}

void searchmiddle(node* head)
{
    if(NULL == head) return;
    else{
    searchmiddle(head->left);
    cout<<head->val<<" ";
    searchmiddle(head->right);
    }
}

void searchlast(node* head)
{
    if(NULL == head) return;
    else{
    searchlast(head->left);///别忘了你一直没调通在哪里???
    searchlast(head->right);///不要万不得已,请不要复制自己写过的代码
    cout<<head->val<<" ";
    }
}

int main()
{
 node* t = createTree();
 searchfirst(t); cout<<endl;
 searchmiddle(t); cout<<endl;
 searchlast(t); cout<<endl;
}

不要复制自己写过的代码~

posted on 2014-05-22 16:14  berkeleysong  阅读(158)  评论(0编辑  收藏  举报

导航