leetcode--124. Binary Tree Maximum Path Sum

Posted Shihu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode--124. Binary Tree Maximum Path Sum相关的知识,希望对你有一定的参考价值。

1、问题描述

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.

For example:
Given the below binary tree,

       1
      /      2   3

Return 6.

2、边界条件:无

3、思路:最大路径值,一个单向路径的最大值已经解决了,一个节点向下的左右两条路径。这道题目可以跨一个节点的两个子节点。这里需要多考虑一个路径,就是左右路径和该节点组成的长路径。另外一点需要注意,一条路径如果<0 ,则可以不连接。需要一个变量来传递当前的最大路径值。

4、代码实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxPathSum(TreeNode root) {
        int[] maxVal = new int[1];
        maxVal[0] = Integer.MIN_VALUE;
        maxPathSum(root, maxVal);
        return maxVal[0];
    }

    public int maxPathSum(TreeNode root, int[] maxVal) {
        if (root == null) {
            return 0;
        }
        int leftMaxVal = Math.max(0, maxPathSum(root.left, maxVal));
        int rightMaxVal = Math.max(0, maxPathSum(root.right, maxVal));
        maxVal[0] = Math.max(maxVal[0], leftMaxVal + rightMaxVal + root.val);
        return Math.max(leftMaxVal, rightMaxVal) + root.val;
    }
}

5、时间复杂度:O(N), 空间复杂度:

6.api:

 


以上是关于leetcode--124. Binary Tree Maximum Path Sum的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode]*124.Binary Tree Maximum Path Sum

[leetcode-124-Binary Tree Maximum Path Sum]

leetcode -124. Binary Tree Maximum Path Sum

LeetCode124. Binary Tree Maximum Path Sum

leetcode--124. Binary Tree Maximum Path Sum

LeetCode124 Binary Tree Maximum Path Sum