[leetcode]Binary Tree Maximum Path Sum

本文介绍了如何使用动态规划和后序遍历来解决二叉树中任意两个节点间的最大路径和问题。通过递归地遍历每个节点,并更新最大路径和,最终得到整个二叉树的最大路径和。

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

Binary Tree Maximum Path Sum

 

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1
      / \
     2   3

Return 6

题目:求任意两个结点间路径的最大和

解题思路:后续遍历二叉树 与 动态规划(一维数组求最大连续子数组和)结合运用。

.

    int innerMaxPathSum(TreeNode *root, int &maxValue){
        int v = root->val;
        int l, r;
        
        maxValue = max(v, maxValue);
        if(NULL == root->left && NULL == root->right){
            return v; //左右子数都为空 即叶结点的情况 直接返回其值 
        }
        if(NULL == root->right){ //只有左子树的情况
            l = innerMaxPathSum(root->left, maxValue);
            maxValue = max(l, maxValue);
            maxValue = max(v + l, maxValue);
            
            return max(v, l + v); //该种情况返回必须包含根结点的路径的最大值, 如果左加根比根小则丢弃根
        }
        if(NULL == root->left){
            r = innerMaxPathSum(root->right, maxValue);
            maxValue = max(r, maxValue);
            maxValue = max(v + r, maxValue); 
            
            return max(v, r + v);//同左
        }
        l = innerMaxPathSum(root->left, maxValue);
        r = innerMaxPathSum(root->right, maxValue);
        
        int oneMaxSum = max(l, r);
        maxValue = max(oneMaxSum, maxValue);
        
        int twoMaxSum = max(l + v, v + r);
        maxValue = max(twoMaxSum, maxValue);
        maxValue = max(l + v + r, maxValue);
        
        return max(twoMaxSum, v);  //同理要包含根结点, 此时有三种情况,要么是根,要么是根左,要么是根右  
    }
    
    int maxPathSum(TreeNode *root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int maxValue = root->val;
        innerMaxPathSum(root, maxValue);
        
        return maxValue;
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值