2023年6月22日发(作者:)
【代码】求⼆叉树叶⼦结点的个数、递归⽅式编写算法,求⼆叉树叶⼦结点的个数题⽬分析:求⼆叉树的叶⼦结点,就是求⼆叉树上左右孩⼦结点都是空的结点,还记得⼆叉树的三种遍历⽅式吗?前序遍历、中序遍历和后序遍历,在递归遍历算法中,⽆论采取哪种遍历⽅式,我们只需要添加⼀个条件就可以求得树的叶⼦结点啦判断是否是叶⼦结点的条件是:题中我采⽤的前序遍历,我们看代码吧建⽴的⼆叉树形状:代码实现:注:此代码除《Domain.h》⾥⾯的算法之外,其余代码皆为⼆叉树的基本操作内容,若有不明⽩的地⽅可参考⽂章:BiTree.h:#pragma once#include#include//结点的结构体struct BiTreeNode{ char data; //数据域 BiTreeNode *LeftChild; //左指针域 BiTreeNode *RightChild;//右指针域};typedef BiTreeNode DataType;//初始化void initiate(BiTreeNode **root){ (*root) = (BiTreeNode*)malloc(sizeof(BiTreeNode)); (*root)->LeftChild = NULL; (*root)->RightChild = NULL;}//在结点的左孩⼦结点插⼊新的数据结点BiTreeNode *LeftInsert(BiTreeNode *root, char data){ if (root == NULL) { printf("未找到当前结点,插⼊失败!n"); return NULL; } BiTreeNode *q = (BiTreeNode*)malloc(sizeof(BiTreeNode)); q->data = data; q->RightChild = NULL; q->LeftChild = root->LeftChild; root->LeftChild = q; return q;}//在结点的右孩⼦结点插⼊新的数据结点BiTreeNode *RightInsert(BiTreeNode *root, char data){ if (root == NULL) { printf("未找到当前结点,插⼊失败!n"); return NULL; } BiTreeNode *q = (BiTreeNode*)malloc(sizeof(BiTreeNode)); q->data = data; q->LeftChild = NULL; q->RightChild = root->RightChild; root->RightChild = q; return q;}//访问数据域void Visit(char data){ printf("%c ", data);}//⼆叉树的前序遍历void PreOrder(BiTreeNode *root){ if (root != NULL) { Visit(root->data); PreOrder(root->LeftChild); PreOrder(root->RightChild); }}Domain.h:#pragma once#include"BiTree.h"/*求⼆叉树叶⼦结点个数,采⽤前序遍历*/int NumOfLeff(DataType *root){ //采⽤static,每次进⼊函数的时候number不会被重新置0 static int number = 0; if (root != NULL) { /*判断为叶⼦结点的条件——没有左右孩⼦结点*/ if (root->LeftChild == NULL && root->RightChild == NULL) number++; NumOfLeff(root->LeftChild); NumOfLeff(root->RightChild); } return number;}main.c:#include"Domain.h"int main(){ DataType *root,*p; initiate(&root); p = root; p = LeftInsert(p, 'A'); p = LeftInsert(p, 'B'); p = LeftInsert(p, 'D'); LeftInsert(p, 'H'); RightInsert(p, 'G'); p = RightInsert(root->LeftChild , 'C'); LeftInsert(p, 'E'); RightInsert(p, 'F'); //以上为创建⼀颗⼆叉树 printf("前序遍历:n"); PreOrder(root->LeftChild); //测试叶⼦结点个数 printf("n叶⼦结点个数:"); printf("%d n", NumOfLeff(root->LeftChild)); system("pause"); return 0;}有需要⾮递归解法的⼩伙伴私信我~代码编译器:Visual Studio 2017ok
发布者:admin,转转请注明出处:http://www.yc00.com/news/1687385190a6115.html
评论列表(0条)