二叉树递归算法:
1.统计二叉树中,度为0的结点个数
2.统计二叉树中,度为1的结点个数
3.统计二叉树中,度为2的结点个数
4.统计二叉树高度
5.统计二叉树宽度
6.删除二叉树中所有叶子节点
7.交换每个节点的左右子女
#include <stdio.h>
#include <stdlib.h>
int s[20]={0};
typedef struct BiTNode{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
BiTree CreateBiTree( ){
char ch;
scanf("%c",&ch);
if(ch=='#') return NULL;
else{
BiTree T = (BiTree)malloc(sizeof(BiTNode));
T -> lchild = T -> rchild = NULL;
T->data = ch;
T->lchild = CreateBiTree();
T->rchild = CreateBiTree();
return T;
}
}
//统计二叉树中度为0的结点个数
int Degree_0(BiTree T){
if(T==NULL) return 0 ;
if( T->lchild==NULL && T->rchild == NULL )
return 1 + Degree_0(T->lchild )+ Degree_0(T->rchild) ;
else
return Degree_0(T->lchild )+ Degree_0(T->rchild) ;
}
//统计二叉树中度为1的结点个数
int Degree_1(BiTree T){
if(T==NULL) return 0 ;
if(( T->lchild!=NULL && T->rchild == NULL ) ||( T->lchild==NULL && T->rchild != NULL ) )
return 1 + Degree_1(T->lchild )+ Degree_1(T->rchild) ;
else
return Degree_1(T->lchild )+ Degree_1(T->rchild) ;
}
//统计二叉树中度为2的结点个数
int Degree_2(BiTree T){
if(T==NULL) return 0 ;
if( T->lchild!=NULL && T->rchild != NULL )
return 1 + Degree_2(T->lchild )+ Degree_2(T->rchild) ;
else
return Degree_2(T->lchild )+ Degree_2(T->rchild) ;
}
//统计二叉树高度
int Depth( BiTree T ){
int ldept , rdept ;
if(T == NULL) return 0;
else{
ldept = Depth(T->lchild);
rdept = Depth(T->rchild);
return (ldept>rdept?ldept:rdept)+1;
}
}
//统计二叉树宽度
void Width( BiTree T ,int deep){
if(T == NULL) return ;
else{
s[deep]++ ;
Width( T->lchild , deep +1 );
Width( T->rchild , deep +1 );
}
}
//交换二叉树中左右子女
void swap(BiTree T){
BiTNode *p ;
if(T){
swap(T->lchild);
swap(T->rchild);
p = T->lchild ;
T->lchild = T->rchild ;
T->rchild = p ;
}
}
//删除二叉树所有叶节点
void Delete_leaves(BiTree T){
if( T ){
if(T->lchild){
if(T->lchild->lchild==NULL&&T->lchild->rchild==NULL){
free(T->lchild);
T->lchild=NULL ;
}
else
Delete_leaves(T->lchild);
}
if(T->rchild){
if(T->rchild->lchild==NULL&&T->rchild->rchild==NULL){
free(T->rchild);
T->rchild=NULL ;
}
else
Delete_leaves(T->rchild);
}
}
}
void PreOrderTraverse(BiTree T){
if(T){
printf("%c",T->data);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
}
int main(){
printf("输入各节点:\n");
BiTree T = CreateBiTree();
printf("度为0的结点个数:%d \n",Degree_0(T));
printf("度为1的结点个数:%d \n",Degree_1(T));
printf("度为2的结点个数:%d \n",Degree_2(T));
printf("二叉树高度:%d \n",Depth(T));
Width(T,0);
int max=0;
for(int i=0;s[i]!=0;i++)
{
if(s[i]>max)
max=s[i];
}
printf("二叉树宽度:%d \n",max);
printf("交换二叉树左右子树:");
PreOrderTraverse(T);printf("\n");
Delete_leaves(T);
printf("删除叶子节点:");
PreOrderTraverse(T);
printf("\n");
swap(T);
}