参考文章:点一下
1.通过前序序列和中序序列建立二叉树
#include<bits/stdc++.h>
using namespace std;
typedef struct node{
char data;
struct node *left;
struct node *right;
}Tree;
string a;
string b;
//根据前序和中序建立二叉树
Tree *bulid(int l1,int l2,int r1,int r2)
{
if(l1>l2)
{
return NULL;
}
Tree *root=new Tree();
root->data=a[l1];
int p=0;
while(root->data!=b[p])
{
p++;
}
int llem=p-r1;
root->left=bulid(l1+1,l1+llem,r1,r1+p-1);
root->right=bulid(l1+llem+1,l2,p+1,r2);
}
void xian(Tree *root)
{
if(root!=NULL)
{
xian(root->left);
xian(root->right);
printf("%c",root->data);
}
}
int main()
{
Tree *root;
root=NULL;
cin>>a;
cin>>b;
int m,n;
m=a.size();
n=b.size();
root=bulid(0,m-1,0,n-1);
xian(root);
}
通过中序序列和后序序列建立树
下面代码是将前序序列输出出来的
#include<bits/stdc++.h>
using namespace std;
char pre[40];
char in[40];
int len;
typedef struct BiNode{
char data;
struct BiNode *lchild;
struct BiNode *rchild;
}Tree;
//根据中序序列和后序序列建树
Tree *bulid2(int l1,int r1,int l2,int r2)
{
//cout<<l1<<' '<<r1<<' '<<l2<<' '<<r2<<endl;
if(r2<l2)
{
//cout<<"NULL"<<endl;
return NULL;
}
Tree *root=new Tree();
root->data=in[r2];
// cout<<in[r2]<<endl;
int p=0;
while(pre[p]!=root->data)
{
p++;
}
int llen=p-l1;
root->lchild=bulid2(l1,p-1,l2,l2+p-l1-1);
root->rchild=bulid2(p+1,r1,l2+p-l1,r2-1);
return root;
/* 测试数据
DCBAEFG
DCBGFEA
*/
}
void postOrder(Tree* root){
if(root!=NULL){
cout<<root->data;
postOrder(root->lchild);
postOrder(root->rchild);
}
}
int main()
{
while(gets(pre)!=NULL){
len=strlen(pre);
gets(in);
Tree *root=bulid2(0,len-1,0,len-1);
postOrder(root);
cout<<endl;
}
return 0;
}