首页 > 其他 > 详细

leetcode--124. Binary Tree Maximum Path Sum

时间:2017-09-02 00:49:53      阅读:319      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/shihuvini/p/7465510.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!