用C语言写一个函数:该函数的功能为计算二叉树的每一层的元素的个数,并且用当前层数乘以当前层数的元素个数,将所有乘积作加法运算。
时间: 2024-03-14 22:45:08 浏览: 37
好的,下面是用C语言实现的函数代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
int maxDepth(TreeNode* root) {
if (root == NULL) {
return 0;
}
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return (left > right ? left : right) + 1;
}
void countNodes(TreeNode* root, int level, int* sums) {
if (root == NULL) {
return;
}
sums[level]++;
countNodes(root->left, level + 1, sums);
countNodes(root->right, level + 1, sums);
}
int getSum(int* sums, int depth) {
int sum = 0;
for (int i = 1; i <= depth; i++) {
sum += i * sums[i];
}
return sum;
}
int main() {
// 构造一棵二叉树
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->val = 4;
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right->val = 5;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 6;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 7;
// 计算二叉树的深度
int depth = maxDepth(root);
// 统计每一层的元素个数
int* sums = (int*)calloc(depth + 1, sizeof(int));
countNodes(root, 1, sums);
// 计算每层元素个数与层数的乘积的和
int sum = getSum(sums, depth);
// 输出结果
printf("The sum of every level's node count times level is %d.\n", sum);
// 释放内存
free(sums);
free(root->left->left);
free(root->left->right);
free(root->right->left);
free(root->right->right);
free(root->left);
free(root->right);
free(root);
return 0;
}
```
在上面的代码中,我们先构造了一棵二叉树,然后使用`maxDepth`函数计算二叉树的深度。接着,我们使用`countNodes`函数统计二叉树每一层的元素个数,并将结果存储在`sums`数组中。最后,我们使用`getSum`函数计算每层元素个数与层数的乘积的和,并输出结果。
需要注意的是,在程序结束之前,我们需要释放二叉树占用的内存。
阅读全文