# 创建二叉树

``````#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
typedef char ElemType;
#define SizeMax 205
int max1=0;
typedef struct Node
{
ElemType data;
Node* lchild;
Node* rchild;
} TBNode;
TBNode*bt2(char*post,char *in,int n)
{
TBNode *b;
char r,*p;
int k;
if(n<=0)return NULL;
r=*(post+n-1);
b=(TBNode *)malloc(sizeof(TBNode));
b->data=r;
for(p=in;p<in+n;p++)
if(*p==r)break;
k=p-in;
b->lchild=bt2(post,in,k);
b->rchild=bt2(post+k,p+1,n-k-1);
return b;
}
void DispTBNode(TBNode*b)
{
if(b!=NULL)
{
printf("%c",b->data);
if(b->lchild!=NULL||b->rchild!=NULL)
{
printf("(");
DispTBNode(b->lchild);
if(b->lchild!=NULL)printf(",");
DispTBNode(b->lchild);
printf(")");
}
}
}
int main()
{
char a[]={'c','b','e','d','a','h','g','i','j','f'};
char b[]={'c','e','d','b','h','j','i','g','f','a'};
TBNode *Tree;
Tree=bt2(b,a,10);
DispTBNode(Tree);
return 0;
}
``````

``````#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
typedef char ElemType;
#define SizeMax 205
int max1=0;
typedef struct Node
{
ElemType data;
Node* lchild;
Node* rchild;
} TBNode;
TBNode*bt2(char*post,char *in,int n)
{
TBNode *b;
char r,*p;
int k;
if(n<=0)return NULL;
r=*(post+n-1);
b=(TBNode *)malloc(sizeof(TBNode));
b->data=r;
for(p=in;p<in+n;p++)
if(*p==r)break;
k=p-in;
b->lchild=bt2(post,in,k);
b->rchild=bt2(post+k,p+1,n-k-1);
return b;
}
void DispTBNode(TBNode*b)
{
if(b!=NULL)
{
printf("%c",b->data);
if(b->lchild!=NULL||b->rchild!=NULL)
{
printf("(");
DispTBNode(b->lchild);
if(b->lchild!=NULL)printf(",");
DispTBNode(b->lchild);
printf(")");
}
}
}
int main()
{
char a[]={'c','b','e','d','a','h','g','i','j','f'};
char b[]={'c','e','d','b','h','j','i','g','f','a'};
TBNode *Tree;
Tree=bt2(b,a,10);
DispTBNode(Tree);
return 0;
}
``````