二叉树的终端节点也称二叉树的叶子,求二叉树的叶子数可以采用任何遍历算法,下面是求二叉树叶子数的一个例子:
#include<stdio.h>
#include<stdlib.h>
typedef struct binode{
char data;
struct binode *lchild, *rchild;
}bitnode, *bitree;
bitree createbitree()
{
bitree t;
char ch;
printf("input a character\n");
fflush(stdin);
scanf("%c",&ch);
if(ch==' '){
t = NULL;
printf("end input\n");
}
else
{
t=(bitree)malloc(sizeof(bitnode));
t->data = ch;
t->lchild = createbitree();
t->rchild = createbitree();
}
return t; // 这个 return t 是返回根节点
}
int countleaf(bitree t, int num)
{
if(t!=NULL)
{
if(t->lchild == NULL && t->rchild == NULL) num++;
num = countleaf(t->lchild, num);
num = countleaf(t->rchild,num);
}
printf("num has return\n");
return num;
}
int main()
{
bitree root;
int count = 0;
printf("\n");
root = createbitree();
count = countleaf(root,count);
printf("leaves = %d\n", count);
system("pause");
return 0;
}
刚开始接触二叉树,对二叉树的创建那一块还不是很熟悉,所以就研究了一下,下面是自己对二叉树创建那一块的领悟,个人见解,欢迎共同讨论,这里我创建了一个简单的二叉树,形状如下图:
其中 D 代表 data,L 代表 lchild,R 代表 rchild, N 代表 NULL,首先输入一个字符,创建一个根节点 1,开辟一段内存空间,把字符复制给根节点 1 的 data,接着第一次递归调用来创建左子树,此时再一次输入一个字符,创建根节点 2,此时,计算机又开辟了一段内存空间,把这次输入的字符复制给根节点 2 的 data,此时程序继续进行第一个的递归,继续输入 一个字符,赋值给节点 4 的 data,然后仍然进行第一个的递归,这一次,我们输入一个空格,计算机不再分配内存空间,程序返回 t->lchild 的值(NULL)给第 4 个节点的 lchild,程序继续往下运行,执行第二个递归,仍然返回 NULL,程序继续往下运行,注意:这个时候,程序会跑到 第一个递归函数那里去执行,因为这里面的 t 只是一个形式,在这个程序中,计算机总共开辟了 3 块地址,1,2,4,此时的 t 是第四个节点内存地址的值,仍然是一个指针,t 的值是没变的,只不过在这个过程中,利用 t 把第四个节点的值给改变了,那么 return t 后是返回到上一层节点上的 lchild 上面的,然后依次往上一层节点返回,函数返回值一定是返回调用该函数的地方,因为当输入的是一个字符的时候,每次执行的都是第一次递归调用,当输入为空的时候,执行第二次递归调用,所以在返回的时候,都是依次的往上一次的调用返回