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:

 

posted on 2017-09-02 00:04  Shihu  阅读(153)  评论(0编辑  收藏  举报

导航