文章
103
粉丝
0
获赞
0
访问
4.0k
(1)递归实现
归思想:
定义一个递归函数,该函数接收当前结点指针和当前结点的深度作为参数。
当前结点权值 * 当前深度
。(2)
typedef struct Bitree{
int weight;
struct Bitree *lchild,*rchild;
}Bitree,*Bitree;
(3)
#include <iostream>
// 假设我们已经定义了结点结构,如上面所示
typedef struct BiTNode {
int weight; // 结点的权值,如果是叶结点则有效,非叶结点可以忽略或设置为0
struct BiTNode *lchild, *rchild; // 左右孩子指针
} BiTNode, *BiTree;
// 辅助函数:创建新结点(方便测试)
BiTree createNode(int w) {
BiTree newNode = new BiTNode;
newNode->weight = w;
newNode->lchild = NULL;
newNode->rchild = NULL;
return newNode;
}
/**
* @brief 递归计算二叉树的带权路径长度(WPL)
* @param root 指向当前子树根结点的指针
* @param depth 当前结点在二叉树中的深度(根结点深度为0)
* @return 当前子树中所有叶结点的带权路径长度之和
*/
long long calculateWPL(BiTree root, int depth) {
long long wpl = 0; // 初始化当前子树的WPL
...
登录后发布评论
暂无评论,来抢沙发