您的位置:首页 > 编程语言 > Java开发

[LeetCode][Java] Binary Tree Maximum Path Sum

2015-07-26 22:02 211 查看

题目:

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:

Given the below binary tree,
1
/ \
2   3


Return
6
.

题意:

给定一棵二叉树,找出最大得路径和。

路径的起始和结束位置可以是树中的任意节点。

比如,

给定如下的一棵二叉树

1
/ \
2   3

返回
6
.

算法分析:

1) Recursively solve this problem

2) Get largest left sum and right sum

3) Compare to the stored maximum

* 这里有一个地方要想明白,最短路径结果有四种可能,当前加左,当前加右,当前自己,当前加左、右子树的return值

* 而return值,有三种可能,当前加左,当前加右,当前自己。

* 这里return里不是当前加左右子树,也就是不能把left和right加起来了...因为只是一条路..,故不符合题目要求。

* 在这里,函数的返回值定义为以自己为根的一条从根到子结点的最长路径

AC代码:

<span style="font-family:Microsoft YaHei;font-size:12px;">/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
public int maxPathSum(TreeNode root)
{
int max[] = new int[1];
max[0] = Integer.MIN_VALUE;
calculateSum(root, max);
return max[0];
}

public int calculateSum(TreeNode root, int[] max)
{
if (root == null)
return 0;

int left = calculateSum(root.left, max);
int right = calculateSum(root.right, max);

int current = Math.max(root.val, Math.max(root.val + left, root.val + right));

max[0] = Math.max(max[0], Math.max(current, left + root.val + right));

return current;
}
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: