[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);//深度
void DeleteXTree(BiTree &T,char X);//除二叉树中以X为根的子树
void DeleteBiTree(BiTree &T);
int main()
{
BiTree T1;char s1[]="ABXE##F##D##CXH##X##G##";char s2='X';char s3='B';
CreateBiTree(T1,s1);
cout<<"二叉树(广义表形式)为:";
BiTreeLists(T1);
cout<<endl;
cout<<"删除二叉树中以"<<s2<<"为根的子树:"; DeleteXTree(T1,s2); BiTreeLists(T1);cout<<endl;
cout<<"删除二叉树中以"<<s3<<"为根的子树:"; DeleteXTree(T1,s3); BiTreeLists(T1);cout<<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<<')';
}
}
void DeleteBiTree(BiTree &T)
{
if(!T)return;
DeleteBiTree(T->lc);
DeleteBiTree(T->rc);
T=NULL;
}
void DeleteXTree(BiTree &T,char X)
{
if(!T) return;
if(T->data==X) DeleteBiTree(T);
else
{
DeleteXTree(T->lc,X);
DeleteXTree(T->rc,X);
}
}