【LeetCode】#124二叉树中的最大路径和(Binary Tree Maximum Path Sum)

【LeetCode】#124二叉树中的最大路径和(Binary Tree Maximum Path Sum)

题目描述

给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

示例

示例 1:

输入: [1,2,3]
1
/
2 3
输出: 6

示例 2:

输入: [-10,9,20,null,null,15,7]
-10
/
9 20
/
15 7
输出: 42

Description

Given a non-empty 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.

Example

Example 1:

Input: [1,2,3]
1
/
2 3
Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]
-10
/
9 20
/
15 7
Output: 42

解法

class Solution {
    int res;
    public int maxPathSum(TreeNode root) {
        res = root.val;
        helper(root);
        return res;
    }
    public int helper(TreeNode node){
        int sum;
        if(node.left==null && node.right==null){
            sum = node.val;
        }else if(node.left==null){
            int right = helper(node.right);
            sum = right>0 ? right+node.val : node.val;
        }else if(node.right==null){
            int left = helper(node.left);
            sum = left>0 ? left+node.val : node.val;
        }else{
            int left = helper(node.left);
            int right = helper(node.right);
            res = Math.max(res, left+right+node.val);
            int max = Math.max(left, right);
            sum = max>0 ? max+node.val : node.val;
        }
        res = Math.max(res, sum);
        return sum;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值