[c++]代码库
#include <iostream>
using namespace std;
typedef char TElemType;
typedef struct BiTNode
{
TElemType data;
BiTNode *lc,*rc;
}*BiTree;
void CreateBiTree(BiTree &T,char s[]);//带有空子树信息的先序建立二叉树
void CreateBiTree(BiTree &T,char s[],int &i);
void BiTreeLists(BiTree &T);//广义表形式
int* LookforX(BiTree &T,char X);
int main()
{
BiTree T1,T2;char s1[]="aX###";char s2[]="ABC###DE##F##";char x1='X';char x2='m';char x3='a';
CreateBiTree(T1,s1);CreateBiTree(T2,s2);
cout<<"二叉树(广义表形式)为:";
BiTreeLists(T1);
cout<<endl;
cout<<"元素为"<<x1<<"的结点的地址:"<<LookforX(T1,x1)<<endl;
cout<<"元素为"<<x3<<"的结点的地址:"<<LookforX(T1,x3)<<endl;
cout<<"二叉树(广义表形式)为:";
BiTreeLists(T2);
cout<<endl;
cout<<"元素为"<<x2<<"的结点的地址:"<<LookforX(T2,x2)<<endl;
return 0;
}
void CreateBiTree(BiTree &T,char s[],int &i)
{
i++;
if(s[i]=='#'){T=NULL;return;}
T=new BiTNode; T->data=s[i];
CreateBiTree(T->lc,s,i);
CreateBiTree(T->rc,s,i);
}
void CreateBiTree(BiTree &T,char s[])
{
int i=-1;
CreateBiTree(T,s,i);
}
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<<')';
}
}
int* LookforX(BiTree &T,char X)
{
if(!T) return NULL;
if(T->data==X) return (int*)T;
int* p;p=LookforX(T->lc,X);
return p!=NULL?p: LookforX(T->rc,X);
}