带权值二叉树的路径最长值与路径

这是一篇关于如何在带有权重的二叉树中找到路径最大权重的问题解析。文章提出了两种方法,第一种方法能求出最大权重但无法显示路径,而第二种方法不仅能找出最大权重,还能记录并展示出这条最大权重的路径。

一、Problem

Given a binary tree, every node has a weight, then you need to find out the path that can make the total weight of all nodes it go through is the maximum and show the path. The weight is always positive.

二、Solution

方法一、 (该方法只能找到路径最大值并不能表示最大值的路径)

int getPath(TreeNode* root, int now) {
    if (root != NULL) {
        int lnow = getPath(root->lchild, root->data);
        int rnow = getPath(root->rchild, root->data);
        int nows = lnow > rnow ? lnow : rnow;
        return now + nows;
    } else {
        return now;
    }
}


int findMaxPath(TreeNode *root) {
    if (root != NULL) {
        int lnow = getPath(root->lchild, root->data);
        int rnow = getPath(root->rchild, root->data);
        int now = lnow > rnow ? lnow : rnow;
        return now;
    } else {
        return 0;
    }
}

方法二、(该方法可以找到最大值且可以输出节点数据,不过得设置一个全局变量sum)

int sum = 0;
int height(TreeNode *t) {  //递归求树高
    int hl,hr;
    if(t == NULL) {
        return 0;
    }
    hl = height(t->lchild)+1;               //最下面的左孩子加一
    hr = height(t->rchild)+1;               //最下面的右孩子加一
    return (hl > hr?hl:hr);                 //比较谁大就取谁
}

void longest_path(TreeNode *root) {  //递归求最长路径
    if (t!= NULL) {
        cout << root->data << " ";  //  输出节点数据
        sum += root->data;// 计算路径最大值                
        if (height(root->lchild) > height(root->rchild)) {   
            longest_path(root->lchild);
        } else {
            longest_path(root->rchild);
        }
    } 
} 

上述两种方法各取所需喽!如有更好的方法欢迎欢迎
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值