前序和中序转换成二叉树

#include<iostream>
#include<iomanip>
#include<list>
#include<cmath>
#include<vector>
#include<assert.h>
#include"Test.h"
using namespace std;
struct Node
{
    int data;
    Node *left;
    Node *right;
};
int pre[]={1,2,4,7,3,5,6,8};
int mid[]={4,7,2,1,5,3,8,6};

Node *f(int pre[],int a,int b,int mid[],int m,int n)
{
    if(b-a+1!=n-m+1)
        throw std::exception("Invalid input!");
    if(a>b||m>n)
        return NULL;
    int i;
    Node *p=NULL;
    for(i=m;i<=n;i++)
    {
        if(mid[i]==pre[a])
        {
            p=new Node();
            p->data=mid[i];
            p->left=f(pre,a+1,a+i-m,mid,m,i-1);
            p->right=f(pre,a+i-m+1,b,mid,i+1,n);
            return p;
        }
    }
    throw std::exception("Invalid input!");
}
Node *Construct(int pre[],int m,int mid[],int n)
{
    if(pre==NULL||mid==NULL||m!=n||m<0)
        throw std::exception("Invalid Input");
    return f(pre,0,m-1,mid,0,n-1);
}

Node *t;
void main()
{ 
    try
    {
        t=Construct(pre,8,mid,8);
    }
    catch(std::exception e)
    {
        cout<<e.what()<<endl;
    }
    int a;

    system("pause");
}

 

posted on 2013-07-22 22:49  dyc0113  阅读(226)  评论(0编辑  收藏  举报

导航