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

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

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

程序实现:

#include <iostream>

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<<root->num<<endl;
            cout<<"wrong1 input"<<endl;
            return NULL;
        }
    }

    int *rootInorder=start_in;
    while(rootInorder<=end_in&&(*rootInorder)!=rootvalue)
        rootInorder++;
    if(rootInorder==end_in&&(*rootInorder)!=rootvalue)
    {
        cout<<"wrong2 input"<<endl;
        return NULL;
    }


    int leftLength=rootInorder-start_in;

    int *leftPreEnd=start_pre+leftLength;
    if(leftLength>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(leftLength<end_pre-start_pre)
    {
        root->rchild=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<<root->num<<" ";
    presearch(root->lchild);
    presearch(root->rchild);
}


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

void postsearch(PBtree root)
{
    if(root==NULL)
        return ;
    postsearch(root->lchild);
    postsearch(root->rchild);
    cout<<root->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<<endl;
    insearch(root);
    cout<<endl;
    postsearch(root);
    cout<<endl;
    return 0;
}

输出结果:

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

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值