c语言叶子结点的计算,计算一棵给定二叉树的所有结点/叶子结点

【2005 三 6】

两种方案计算二叉树各结点的子孙个数的算法

【测试数据】来源:https://blog.csdn.net/weixin_42034217/article/details/95787182

cc41b4809840be2216fee83df08c1dbe.png

【代码解析】

#include #include #define maxsize 100

// 定义结点类型

typedef struct btnode

{

int data;

int count;

struct btnode *lchild, *rchild;

} btnode;

FILE *fp;///使用文件读取数据

/*方案一*/

//二叉树

btnode* creat_bitree()

{

int a;

fscanf(fp, "%d", &a);

btnode *node = NULL;

if (a != 0)

{

node = (btnode *)malloc(sizeof(btnode));

node->data = a;

node->lchild = creat_bitree();

node->rchild = creat_bitree();

}

return node;

}

int count_child(btnode*t)

{

int left = 0;

int right = 0;

if (t == NULL)

return 0;

if (t->lchild)

{

left = count_child(t->lchild) + 1;//计算t的左子树根节点的孩子结点的个数+左子树根节点本身

}

if (t->rchild)

{

right = count_child(t->rchild) + 1;//计算右子树孩子结点的个数+右子树根节点本身

}

return left + right;//返回的是t结点孩子结点的个数

}

//前序遍历

void pre1(btnode *bt)

{

if (bt)

{

printf("结点:%d的子孙个数为:%d\n ", bt->data, count_child(bt));

pre1(bt->lchild);

pre1(bt->rchild);

}

}

/*************************************************************/

/*方案2*/

int count_all(btnode* root)

{

if (root == NULL)

return 0;

else

{

int left, right;

left = count_all(root->lchild);//计算根结点左子树整棵树的结点个数总数

right = count_all(root->rchild);//计算右子树结点总数

root->count = left + right;//把根节点孩子结点存进count域中

return left + right + 1;//返回的是整棵树的结点个数

}

}

void pre2(btnode *bt)

{

if (bt)

{

printf("结点:%d的子孙个数为:%d\n ", bt->data, bt->count);

pre2(bt->lchild);

pre2(bt->rchild);

}

}

/*************************************************************/

/*输出两种方案*/

int main()

{

fp = fopen("data.txt", "r");

btnode *bt = creat_bitree();

printf("方案1:\n");

pre1(bt);

printf("\n方案2:\n");

count_all(bt);

pre2(bt);

}

/*建立一个名为data的txt文件,将此文件放在本程序所在文件夹目录下

文件内容(按照二叉树前序序列,0表示空指针域):

55

10

7

3

0

0

0

22

0

0

666

0

1000

0

0

*/

【测试结果】

cae565dc0fd52ac1e4ddd36a18c9bc53.png

【2019】五  二叉树采用二叉链表作为存储结构,写一递归算法计算非叶子结点数。

【代码】

int count(btnode* bt)

{

if (bt == NULL)

return 0;

else if (bt->lchild == NULL && bt->rchild == NULL)

return 0;

else

{

int n1, n2;

n1 = count(bt->lchild);

n2 = count(bt->rchild);

return n1 + n2 + 1;

}

}

【测试结果】利用【2005】例题的数据

4d4ab3ac19e26802dd075024e6564404.png

非叶结点个数为:4

154addd4a2b76bcf71d2f80cba76a29f.png

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值