二叉树最大路径和 Binary Tree Max Path Sum

本文介绍了一种求解二叉树中任意两节点间最大路径和的算法。通过递归方式,自底向上计算经过每个节点的最大路径值,并最终确定整棵树的最大路径和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本题有两个相关问题:1)所求路径可以位于任意两个节点之间(参见leetcode);2)所求路径位于两个叶子节点之间(参见geekforgeeks)。

下面给出问题1)的解法。问题2)的解法可以根据解法1)很容易得出。
问题1)的解法:遍历所有节点,求出经过每一个节点的最大路径,最后再求出经过每个节点的最大路径的最大值。用递归的思路,自底向上递归。

下面是代码:

    void maxPathSumUtil(Node* root, int& left, int& right, int& maxSum);

    int maxPathSum(TreeNode *root) {
    // find out the max path sum between any two nodes in a binary tree
        int maxSum = -10000;
        int left, right;
        
        maxPathSumUtil(root, left, right, maxSum);
        
        return maxSum;
    }
    
    void maxPathSumUtil(TreeNode* root, int& left, int& right, int& maxSum)
    {
    // left will be the max value of a path with root as the right-most node
    // right will be the max value of a path with root as the left-most node
    // maxSum will be the max path value up until now
        if(root==NULL)
        {
            left = 0;
            right = 0;
            return;
        }
        
        int left1, left2, right1, right2;
        
        // traverse the left subtree
        maxPathSumUtil(root->left, left1, right1, maxSum);
        // traverse the right subtree
        maxPathSumUtil(root->right, left2, right2, maxSum);

        // left at least has a value of root->val
        // right at least has a value of root->val        
        left = root->val;
        right = root->val;

        if(max(left1,right1)<=0 && max(left2,right2)<=0)
        {// if so, root will be the starting point of a new path
            maxSum = max(root->val, maxSum);
            return;
        }
        
        if( max(left1,right1)>0 )
        {
            left = left + max(left1,right1);
        }
        
        if( max(left2,right2)>0 )
        {
            right = right + max(left2,right2);
        }
        
        maxSum = max(left+right - root->val, maxSum);
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值