#include <stdio.h>
#include <malloc.h>
typedef struct BTNode
{
char data;
struct BTNode *left, *right;
}BTNode;
BTNode *creat_tree()
{
BTNode *t = NULL;
int x;
//printf ("正在建立一个新二叉树,请输入结点的值:");
scanf ("%d", &x);
if (x == 0) return NULL;
else
{
t = (BTNode *) malloc (sizeof(BTNode));
t -> data = x;
t -> left = creat_tree();
t -> right = creat_tree();
}
return t;
}
//求二叉树各层结点数的最大值,即二叉树的宽度
//思路:对二叉树进行层次遍历,并用一个数组存储各结点所在的层数k,
//扫描该数组,n为k出现的次数,max为最大的n;
typedef struct
{
int front, rear;
BTNode *data[100];
int level[100];
}Queue;
int density(BTNode *bt)
{
if (bt == NULL) return 0;
else{
BTNode *lastnode = bt;
BTNode *newlastnode = NULL;
int a[100];
int k, i, max, n;
int h = 0;
BTNode *p;
Queue qu;
qu.front = -1, qu.rear = -1;
qu.data[++qu.rear] = bt;
qu.level[qu.rear] = 1;
while (qu.front != qu.rear)
{
p = qu.data[++qu.front];
k = qu.level[qu.front];
if (p->left != NULL)
{
qu.data[++qu.rear] = p->left;
newlastnode = p->left;
qu.level[qu.rear] = k+1;
}
if (p->right != NULL)
{
qu.data[++qu.rear] = p->right;
newlastnode = p->right;
qu.level[qu.rear] = k+1;
}
if (p == lastnode)
{
lastnode = newlastnode;
h++;
}
}
max = 0, i = 0;
int j=0;
k=1;
while(i<=qu.rear)
{
n=0;
for (j=i; qu.level[i] == k; ++i)
n++;
if (n>max) max=n;
k++;
}
return h*max;
}
}
void main()
{
BTNode *tree = creat_tree();
int den = density(tree);
printf ("%d", den);
}
6.52√ 计算二叉树的繁茂度
最新推荐文章于 2021-07-16 15:01:48 发布