一、二叉树的深度、叶子结点和总结点个数
参考书(《数据结构(C语言)》–严蔚敏等编著,清华大学出版社);
一、深度、叶子结点和总结点
叶子结点:度为0的节点称为叶子结点;
总结点:二叉树所有节点之和;
深度:树中节点的最大层次称为树的深度;
相关代码:
#include "stdio.h"
#include "stdlib.h"
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef char TElemType;
typedef struct BiNode {
TElemType data; //数据域
struct BiNode *lchild, *rchild; //左右孩子指针
} BiNode, *BiTree;
Status CreateBiTree(BiTree &T);
//构造二叉链表的二叉树T
Status CreateBiTree(BiTree &T) {
//按 先序次序输入二叉树中节点的值,#代表空树
char ch;
scanf("%c",&ch);
if(ch == '#') T=NULL;
else {
if(!(T = (BiNode *)malloc(sizeof(BiNode)))) exit(OVERFLOW);
T->data = ch; //生成树根节点
CreateBiTree(T->lchild); //构造左子树
CreateBiTree(T->rchild); //构造右子树
}
return OK;
}
Status TreeDepth(BiTree T);
//统计二叉树的深度(递归)
Status TreeDepth(BiTree T) {
int leftHeight, rightHeight, maxHeight; //左子树,右子树,最大深度
if(T==NULL) return 0; //空,深度=0
else {
leftHeight = TreeDepth(T->lchild); //左子树深度
rightHeight = TreeDepth(T->rchild); //右子树深度
maxHeight = leftHeight>rightHeight ? leftHeight:rightHeight; //最大深度
return maxHeight+1; //二叉树深度=最大深度+1(总根节点算一层)
}
}
Status NodeCount(BiTree T);
//统计树的叶子结点个数 (递归)
Status NodeCount(BiTree T) {
if(T==NULL) {
return 0; //空,叶子节点=0
} else {
if((NodeCount(T->lchild)==NULL) && (NodeCount(T->rchild)==NULL)) {
return 1; //表示此(根)节点为一个叶子节点
} else return NodeCount(T->lchild) + NodeCount(T->rchild);
}
}
Status TreeCount(BiTree T);
//统计树的结点个数
Status TreeCount(BiTree T) {
int lefttree,righttree; //左子树节点个数,右子树节点个数
if(T==NULL) {
return 0; //空,节点sum=0
} else {
lefttree=TreeCount(T->lchild); //根的左子树节点数
righttree=TreeCount(T->rchild); //根的右子树节点数
return lefttree+righttree+1; //左+右+总根节点
}
}
int main(void) {
BiTree T;
CreateBiTree(T);
printf("%d\n",TreeDepth(T));
printf("%d\n",NodeCount(T));
printf("%d\n",TreeCount(T));
return OK;
}
/*
测试输入:ABC##D##E##
预期输出:
3
3
5
提示:
第一行输出是二叉树的深度
第二行输出是二叉树的叶子结点数
第三行输出是二叉树的结点数
*/
实现:
初始二叉树为:
ABC##D##E##
如图:
ABCD###E##FG###
如图: