《剑指offer》面试题6 重建二叉树

#include <iostream>

using namespace std;
typedef struct Binary_Node
{
    int value;
    struct Binary_Node *left;
    struct Binary_Node *right;
}BinaryNode;
int pre_order[1010];
int in_order[1010];
int flag;
BinaryNode *BuildTree(int *start_pre,int *end_pre,
                      int *start_in,int *end_in)
{
    BinaryNode *root=new BinaryNode;
    root->value=*start_pre;
    root->left=root->right=NULL;
    if(start_pre== end_pre)
    {
        if(start_in==end_in && *start_pre==*start_in)
            return root;
        else
        {
            flag=0;

        }
    }
    //在中跟序列中找到根节点的值
    int *rootInOrder=start_in;
    while(rootInOrder<=end_in&& *rootInOrder!=root->value)
        rootInOrder++;

    int leftLength  = rootInOrder-start_in;
    int rightLength = end_in - rootInOrder;
    int *leftPriEnd = start_pre+leftLength;
    if (leftLength >0)
    {
        root->left= BuildTree(start_pre+1,leftPriEnd,start_in,rootInOrder-1);
    }
    else
    {
        //flag=0;
    }
    if(leftLength<end_pre- start_pre)
    {
        root->right=BuildTree(leftPriEnd+1,end_pre,rootInOrder+1,end_in);
    }
    else
    {
        //flag=0;

    }
    return root;
}
void print(BinaryNode *root)
{
    if(root!=NULL)
    {


        print(root->left);
        print(root->right);
        if(root!=NULL)
        {
            cout<<root->value<<' ';
        }
    }
}
int main()
{
    int length;
    while(cin>>length)
    {
        for(int i=0;i<length;i++)
            cin>>*(pre_order+i);
        for(int i=0;i<length;i++)
            cin>>*(i+in_order);
        flag=1;
        BinaryNode *node=new BinaryNode;
        int *start_pre=&pre_order[0];
        int *end_pre  =&pre_order[length-1];
        int *start_in =&in_order[0];
        int *end_in   =&in_order[length-1];
        node=BuildTree(start_pre,end_pre,start_in,end_in);
        if (flag)
        {
            print(node);
            cout<<endl;
        }
        else cout<<"No"<<endl;
    }

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值