先序遍历创建二叉链表
算法描述
void CreateBiTre(BiTree &T){
//按先序顺序输入二叉树中结点的值(一个字符),创建二叉链表表示的二叉树T
cin>>ch;
if(ch==’#’)
T==NULL;
else{
T=new BiTNode;
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(Tlchild);
}
}
复制二叉树
算法描述
void Copy(BiTree T,BiTree &NewT){
if(T==NULL){
NewT=NULL;
return;
}
else{
NewT=new BiTode;
NewT->data=T->data;
Copy(T->lchild,NewT->child); //递归复制左子树
Copy(T->rchild,NewT->rchild);//递归复制右子树
}
}
计算二叉树的深度
算法描述
int Depth(BiTree T){
if(T==NULL)
return 0;
else{
m=Depth(T->lchild); //递归计算左子树的深度,记为m
n=Depth(T->rchild); //递归计算右子树的深度,记为n
if(m>n) return m+1;
else return n+1;
}
}
统计二叉树结点个数
算法描述
int NodeCount(BiTree T){
if(T==Null) return 0;
else
return NodeCount(T->lchild)+NodeCount(T->rchild);
}
总结,在二叉树中的应用一般使用递归算法.