1、求度为0(叶子结点)的结点个数?***
//1.二叉树求叶子个数(度为0)
//算法思想:用递归,左右子树都是空就是叶子
typedef struct BTNode{
int data;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode,*BiTree;
void leafcount(BiTree T,int &count){
if(T){
if((T->lchild==NULL)&&(T->rchild==NULL))
count++;
else{
leafcount(T->lchild,count);
leafcount(T->rchild,count);
}
}
}
//2.用孩子兄弟链表求叶子个数
typedef struct HXNode{
int data;
struct HXNode *firstchild;
struct HXNode *nextsibling;
}HXNode,*HXTree;
void leafcount(HxTree T,int *count){
if(T){
if(T->firstchild=NULL)
*count++; //没有孩子就是叶子
leafcount(T->firstchild,count);
leafcount(T->nextsibling,count);
}
else{return 0;}
}
2、求度为1的结点个数?*
//二叉树求度为1个数
//算法思想:用递归,01或10就是度为1
typedef struct BTNode{
int data;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode,*BiTree;
void D1(BiTree T,int &count){
if(T==NULL){return 0;}
if((T->lchild==NULL&&T->rchild!=NULL)||(T->lchild!=NULL&&T->rchild==NULL)){
return D1(T->lchild)+D1(T-rchild)+1;
}
else{
return D1(T->lchild)+D1(T->rchild);
}
}
3、求度为2的结点个数?**
//算法思想:求度为2,即左右孩子均不为空
typedef struct BTNode{
int data;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode,*BiTree;
void D2(BiTree T,int &count){
if(!T){return 0;}
if(T->lchild!=NULL&&T->rchild!=NULL)
return D2(T->lchild)+D2(T->rchild)+1;
else{
return D2(T->lchild)+D2(T->rchild);
}
}
4、求叶子和非叶子结点个数?**
void count(BiTree T, int *n,*n0){
if(T){
if(T->lchild==NULL&&T->rchild==NULL){
*n0++;
}
else{ n++;} //除了叶子就是非叶子
count(T->lchild,n,n0);
count(T->rchild,n,n0);
}
}
5、求二叉树结点数?*
int n;
void count(BTree *p){
if(p){
++n;
count(p->lchild);
count(p->rchild);
}
}
6、求二叉树深度?**
//1、二叉树求深度
int depth(BiTree T){
if(!T)
return 0;
else{
int ldeep=depth(T->lchild);
int rdeep=depth(T->rchild);
deep=1+(ldeep > rdeep ? ldeep : rdeep);
} //把根结点加上
return deep;
}
//2、孩子兄弟法求深度
typedef struct HXNode{
int data;
struct HXNode *firstchild;
struct HXNode *nextsibling;
}HXNode,*HXTree;
int depth(HXTree T){
if(!T)
return 0;
else{
int ldeep=depth(T->firstchild)+1; //左孩子是真孩子
int rdeep=depth(T->nextsibling); //右孩子是兄弟
if(ldeep>rdeep)
return ldeep;
else
return rdeep;
}
}
本篇全部使用递归,非递归的后面再写。
数据结构考试二叉树部分(孩子兄弟链表法)最爱考的就是这些,希望对您有用!一起进步!