根据二叉树的先序遍历和中序遍历构建二叉树

问题:根据二叉树的先序和中序构建二叉树

思路:每次根据先序和中序顺序确定根节点和相应的左右子树,再分别对左右子树进行递归确定

程序实现:

#include 

using namespace std;

typedef struct Btree
{
    int num;
    struct Btree *lchild;
    struct Btree *rchild;
}Btree,*PBtree;

PBtree construct_tree(int *start_pre,int *end_pre, int *start_in, int *end_in)
{
    PBtree root;
    root=new Btree();
    int rootvalue=start_pre[0];
    root->num=rootvalue;
    root->lchild=NULL;
    root->rchild=NULL;

    if(start_pre==end_pre)
    {
        if(start_in==end_in &&(*start_pre)==(*start_in))
            return root;
        else
        {
            cout<num<0)
    {
        //root->lchild=construct_tree(start_pre+1,start_pre+leftLength,start_in,rootInorder-1);
        root->lchild=construct_tree(start_pre+1,leftPreEnd,start_in,rootInorder-1);
    }

    if(leftLengthrchild=construct_tree(leftPreEnd+1,end_pre,rootInorder+1,end_in);
    }
    return root;
}


PBtree construct_init(int *preorder,int *inorder,int length)
{

    if(preorder==NULL||inorder==NULL||length<0)
        return NULL;
    return construct_tree(preorder,preorder+length-1,inorder,inorder+length-1);

}

void presearch(PBtree root)
{
    if(root==NULL)
        return ;
    cout<num<<" ";
    presearch(root->lchild);
    presearch(root->rchild);
}


void insearch(PBtree root)
{
    if(root==NULL)
        return ;
    insearch(root->lchild);
    cout<num<<" ";
    insearch(root->rchild);
}

void postsearch(PBtree root)
{
    if(root==NULL)
        return ;
    postsearch(root->lchild);
    postsearch(root->rchild);
    cout<num<<" ";
}

int main()
{
    int a[11]={5,6,1,4,2,3,4,7,8,9,10};
    int b[11]={4,1,6,2,3,5,7,4,8,9,10};

    PBtree root=construct_init(a,b,11);

    presearch(root);
    cout<

输出结果:

5 6 1 4 2 3 4 7 8 9 10
4 1 6 2 3 5 7 4 8 9 10
4 1 3 2 6 7 10 9 8 4 5

 

你可能感兴趣的:(程序设计基础,树)