[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 depth(BiTree T);//深度
int LookforX(BiTree &T,char X);//二叉树中以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<<"二叉树(广义表形式)为:";
BiTreeLists(T2);
cout<<endl;
cout<<"该二叉树中以"<<x2<<"为根的深度为:"<<LookforX(T2,x2)<<endl;
cout<<"该二叉树中以"<<x3<<"为根的深度为:"<<LookforX(T2,x3)<<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 0;
if(T->data==X) return depth(T);
int p;p=LookforX(T->lc,X);
return p!=NULL?p: LookforX(T->rc,X);
}
int depth(BiTree T)
{
int dl,dr;
if(!T) return 0;
dl=depth(T->lc);
dr=depth(T->rc);
return dl>dr?dl+1:dr+1;
}