开始刷leetcode day16:Binary Tree Maximum Path Sum

本文介绍了一种解决二叉树中寻找最大路径和问题的算法实现。该算法通过递归方式遍历树的每个节点,并计算以当前节点为起点的最大路径和,最终返回整棵树的最大路径和。

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

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.



Java:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxPathSum(TreeNode root) {
        if(root == null) return 0;
        int[] max = new int[1];
        max[0] = Integer.MIN_VALUE;
        maxSum(root,max);
        return max[0];
    }
    
    public int maxSum(TreeNode root,int[] max)
    {
        if(root == null) return 0;
      //  if(root.left == null && root.right == null) return root.val>0?root.val:0;
        int leftvalue = maxSum(root.left,max);
        int rightvalue = maxSum(root.right,max);
        int value = Math.max(leftvalue + root.val,rightvalue  + root.val);
        int value2 =  Math.max(value,root.val);
        int value3 = Math.max(value2,leftvalue + root.val + rightvalue);
        max[0] = Math.max(max[0],value3);
        return value2;
    }
}


注意:参考了网上的解法。1,需要用数组进行数值的传值。2,需要比较left+val,right+val,val,left+val+right,oldmax。 3,不能返回value3,因为意味着不能走root的parent了。4,但仍需要考虑value3的状况,所以用存储的max来返回最终的结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值