87.png

    1. /*
    2. 二叉树的带权路径长度(WPL)是二叉树中所有叶节点的带权路径长度之和。给定一颗二叉树T,采用二叉链表存储,节点结构为
    3. left weight right
    4. 试设计求T的WPL的算法
    5. 分析:
    6. 我们求带权路径长度,既需要知道叶节点的权值,也需要知道其经过的路径,我们可以设置一个变量depth代表深度,也就是
    7. 路径长度,设置一个静态变量weight累加带权路径,会使用到递归。
    8. */
    9. struct tree {
    10. int weight;
    11. struct tree *left, *right;
    12. };
    13. #define _CRT_SECURE_NO_WARNINGS
    14. #include <stdio.h>
    15. #include <stdlib.h>
    16. tree *create(tree *T) {//建立一颗二叉树
    17. int weight;
    18. printf("请输入当前节点权值:weight=");
    19. scanf("%d", &weight);
    20. getchar();
    21. if (weight != -1) {
    22. T = (tree *)malloc(sizeof(tree));
    23. T->weight = weight;
    24. T->left = NULL;
    25. T->right = NULL;
    26. T->left = create(T->left);
    27. T->right = create(T->right);
    28. }
    29. return T;
    30. }
    31. int countWPL(tree *T, int depth) {
    32. static int totalWeight = 0;//设置静态变量
    33. if (T) {
    34. if (!T->left && !T->right) {//已经是叶节点
    35. totalWeight += T->weight*depth;//计算带权路径
    36. }
    37. else {
    38. countWPL(T->left, depth + 1);//左子树
    39. countWPL(T->right, depth + 1);//右子树
    40. }
    41. }
    42. return totalWeight;
    43. }
    44. int main() {
    45. struct tree *T = (struct tree *)malloc(sizeof(struct tree));
    46. T = create(T);
    47. int depth = 0;
    48. int totalW;
    49. totalW = countWPL(T, depth);
    50. printf("该二叉树的带权路径长度为:%d", totalW);
    51. return 0;
    52. }