124. Binary Tree Maximum Path Sum
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
Example
Given the below binary tree:
1
/ \
2 3
return 6
.
分析:
这是一道非常好的题,因为如果要求是从root到leaf, 难度会降低不少。但是这题要求可以不包含root,给人感觉不好下手。
但是仔细想想,假设我们找到maximum path,那个path里一定有一个“root”。所以我们可以创建一个方法找出以当前node为root的maximum sum path, 记住,这里的条件是那个maximum path一定要含有当前node。
那么我们是不是要遍历每个node, 然后以每个node作为root来找出全局maximum sum path呢,其实是不用的。这也是下面这题解法很奇妙的地方。这里会用到一个size为1的数组,保存我们在求中间值时找到的maximum path sum.
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 11 public class Solution { 12 public int maxPathSum(TreeNode root) { 13 int max[] = new int[1]; 14 max[0] = Integer.MIN_VALUE; 15 calculateSum(root, max); 16 return max[0]; 17 } 18 19 public int calculateSum(TreeNode root, int[] max) { 20 if (root == null) return 0; 21 22 int left = calculateSum(root.left, max); 23 int right = calculateSum(root.right, max); 24 25 int current = Math.max(root.val, Math.max(root.val + left, root.val + right)); 26 //我们在递归的时候,会把中间找到的maximum path sum记录到max[0]中。 27 max[0] = Math.max(max[0], Math.max(current, left + root.val + right)); 28 29 return current; 30 } 31 }