标签:ini tree 最短路 store bottom style sof problem content
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加起来了...由于仅仅是一条路..,故不符合题目要求。
* 在这里,函数的返回值定义为以自己为根的一条从根到子结点的最长路径
<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>
[LeetCode][Java] Binary Tree Maximum Path Sum
标签:ini tree 最短路 store bottom style sof problem content
原文地址:http://www.cnblogs.com/cynchanpin/p/6745161.html