由中序与先序字符串列获取二叉树
/*
Name: 二叉树
Copyright:
Author:
Date: 18/04/17 16:24
Description: 利用先序与中序二叉树字符串构造二叉树结构
*/
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct tree
{
char data;
struct tree *lc;
struct tree *rc;
}create;
create *createTree(char *pre,char *in,int n)
{
create *b;
char *p;
int k;
if(n<=0)
return NULL;
b=(create *)malloc(sizeof(create));
b->data=*pre;
for(p=in;p<in+n;p++)
if(*p==*pre)
break;
k=p-in;
b->lc=createTree(pre+1,in,k);
b->rc=createTree(pre+k+1,p+1,n-k-1);
return b;
}
int main()
{
char a[7]={'A','B','D','G','C','E','F'};//先序字符串数组
char b[7]={'D','G','B','A','E','C','F'};//中序字符串数组
char *i=a,*j=b;
create *c=createTree(a,b,7);
cout<<" ";
cout<<c->data;//此处用于输出所得到的二叉树
cout<<endl;
cout<<" ";
cout<<c->lc->data;
cout<<" ";
cout<<c->rc->data;
cout<<endl;
cout<<" ";
cout<<c->lc->lc->data;
cout<<" ";
cout<<c->rc->lc->data;
cout<<" ";
cout<<c->rc->rc->data;
cout<<endl;
cout<<" ";
cout<<c->lc->lc->rc->data;
return 0;
}
所得截图如下所示: