【2005 三 6】
两种方案计算二叉树各结点的子孙个数的算法
【测试数据】来源:https://blog.csdn.net/weixin_42034217/article/details/95787182
【代码解析】
#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
*/
【测试结果】
【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】例题的数据
非叶结点个数为:4