二叉树的最长路径和(Binary Tree Maximum Path Sum)

题目:

Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root
google 翻译:
给定一个二叉树,找到最大路径和。 对于这个问题,路径被定义为从父子连接到某个起始节点到树中任何节点的任何节点序列。 该路径必须包含至少一个节点,不需要遍历根。
示例:
这里写图片描述

就是从任意节点开始到任意节点结束所走过的最大距离

思路:
最大值的可能情况,虽然题目说不需要遍历根节点,其实是需要根节点的。
把根节点理解成父节点更好一些,因为需要父节点和别的连成一条线。
最大值来自

  1. root+左边的某条路径+右边的某条路径
  2. 左边的某条路径 + root
  3. root + 右边的某条路径
  4. root
    练习传送门:这里

java实现:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int max = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        record(root);
        return max;
    }
    public int record(TreeNode root){
        if(root==null) return 0;
        int l=Math.max(0,record(root.left));
        int r=Math.max(0,record(root.right));
        max=Math.max(max,root.val+l+r);
        return root.val+Math.max(l,r);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值