[c++]代码库
#include <iostream>
using namespace std;
typedef char TElemType;
typedef struct BiTNode
{
TElemType data;
BiTNode *lc,*rc;
}*BiTree;
void xzCreateBiTree(BiTree &T,char s1[],char s2[],int n);//先序遍历和中序遍历建立二叉树的二叉链表
void BiTreeLists(BiTree &T);//广义表形式输出
int main()
{
BiTree T;int n=8;char s1[]="ACEHFBGD";char s2[]="HECFAGBD";
cout<<"二叉树的先序遍历是:"<<s1<<endl;
cout<<"二叉树的中序遍历是:"<<s2<<endl;
xzCreateBiTree(T,s1,s2,n);
cout<<"该二叉树(广义表形式)为:";
BiTreeLists(T);
cout<<endl;
return 0;
}
void xzCreateBiTree(BiTree &T,char s1[],char s2[],int n)
{
if(n==0){T=NULL;return;}
for(int i=0;i<n;i++)
{
if(s2[i]==s1[0])
{
T=new BiTNode; T->data=s1[0];
xzCreateBiTree(T->lc,s1+1,s2,i);
xzCreateBiTree(T->rc,s1+i+1,s2+1+i,n-i-1);break;
}
}
}
void BiTreeLists(BiTree &T)
{
if(!T) {cout<<'#';return;}
cout<<T->data;
if(T->lc ||T->rc)
{
cout<<'(';
BiTreeLists(T->lc);
cout<<',';
BiTreeLists(T->rc);
cout<<')';
}
}