#include<stdio.h>
#include<stdlib.h>
/***
二叉链表建立二叉树的时候输入为0的时候为空节点
(而空节点下面是不会再有节点的)(输入的是字符,各个字符代表节点)
输入结束时保证构造的二叉树的叶子节点有两个空的子节点。构造的图如下所示:
列如输入为:ABC00DE0G00F000
怎么才能输入结束?因为是递归输入,而最终递归结束的时候输入就结束。
char nd;
struct BiNode *leftChild;
struct BiNode *rightChild;
}BiNode,*BiRoot;
BiRoot biRoot;// 二叉树的根节点指针
char ch;
int num = 0;
int depth = 0;
/** 此处BiRoot 是指针类型
所以下面申请内存的时候 是:sizeof(BiNode) 而不是sizeof(BiRoot)
自行查看sizeof()的作用!
**/
/**注意下面函数中形参是指针类型的引用
若形参只是指针类型,(形参是一个新变量)接收实参传的地址。
请看图理解一下:
**/
// 先序建立二叉树(0代表虚空节点)
void preCreateBiTree(BiRoot &T){
scanf("%c",&ch);
if(ch=='0') T=NULL;
else{
T = (BiRoot)malloc(sizeof(BiNode));
T->nd = ch;
preCreateBiTree(T->leftChild);
preCreateBiTree(T->rightChild);
}
return ;
}
int countLeaves(BiRoot T){
if(T){
// 若是 该节点 没有左右孩子则叶子数+1
if(!T->leftChild&&!T->rightChild) num++;// 何为叶子?叶子就是没有左右孩子。
countLeaves(T->leftChild);
countLeaves(T->rightChild);
}
return num;
}
//树的深度为 左右子树深度的最大值,递归解决
int countDepth(BiRoot T){
if(T==NULL)return 0;
else{
int depth1 = countDepth(T->leftChild);// 左子树的深度
int depth2 = countDepth(T->rightChild);// 右子树的深度
if(depth1>depth2) depth = depth1+1; // 树的深度为 左右子树深度的最大值
else depth = depth2+1;
return depth;
}
}
int main(){
printf("先序建立二叉树:\n");
preCreateBiTree(biRoot);
printf("叶子的个数:");
printf("%d",countLeaves(biRoot));
printf("\n");
printf("树的深度:");
printf("%d",countDepth(biRoot));
}
#include<stdlib.h>
/***
二叉链表建立二叉树的时候输入为0的时候为空节点
(而空节点下面是不会再有节点的)(输入的是字符,各个字符代表节点)
输入结束时保证构造的二叉树的叶子节点有两个空的子节点。构造的图如下所示:
列如输入为:ABC00DE0G00F000
怎么才能输入结束?因为是递归输入,而最终递归结束的时候输入就结束。
**/
char nd;
struct BiNode *leftChild;
struct BiNode *rightChild;
}BiNode,*BiRoot;
BiRoot biRoot;// 二叉树的根节点指针
char ch;
int num = 0;
int depth = 0;
/** 此处BiRoot 是指针类型
所以下面申请内存的时候 是:sizeof(BiNode) 而不是sizeof(BiRoot)
自行查看sizeof()的作用!
**/
/**注意下面函数中形参是指针类型的引用
若形参只是指针类型,(形参是一个新变量)接收实参传的地址。
请看图理解一下:
**/
// 先序建立二叉树(0代表虚空节点)
void preCreateBiTree(BiRoot &T){
scanf("%c",&ch);
if(ch=='0') T=NULL;
else{
T = (BiRoot)malloc(sizeof(BiNode));
T->nd = ch;
preCreateBiTree(T->leftChild);
preCreateBiTree(T->rightChild);
}
return ;
}
int countLeaves(BiRoot T){
if(T){
// 若是 该节点 没有左右孩子则叶子数+1
if(!T->leftChild&&!T->rightChild) num++;// 何为叶子?叶子就是没有左右孩子。
countLeaves(T->leftChild);
countLeaves(T->rightChild);
}
return num;
}
//树的深度为 左右子树深度的最大值,递归解决
int countDepth(BiRoot T){
if(T==NULL)return 0;
else{
int depth1 = countDepth(T->leftChild);// 左子树的深度
int depth2 = countDepth(T->rightChild);// 右子树的深度
if(depth1>depth2) depth = depth1+1; // 树的深度为 左右子树深度的最大值
else depth = depth2+1;
return depth;
}
}
int main(){
printf("先序建立二叉树:\n");
preCreateBiTree(biRoot);
printf("叶子的个数:");
printf("%d",countLeaves(biRoot));
printf("\n");
printf("树的深度:");
printf("%d",countDepth(biRoot));
}