124. Binary Tree Maximum Path Sum

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
1
/ \
2 3

Return 6.

解法1: Divide & Conquer O(N)

对于一个node有左右两边的path,经过这一点的path可以有的情况是,往左,往右,自己,或者从左往右。
如果以left或者right为顶点的maxPath为负数的话,那么包含当前点的maxPath一定不用包含负数的left或者right

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int res = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (root == null) return 0;
helper(root);
return res;
}
private int helper(TreeNode root) {
if (root == null) return 0;
int left = Math.max(0, helper(root.left));
int right = Math.max(0, helper(root.right));
res = Math.max(res, left + right + root.val);
return Math.max(left, right) + root.val;
}
}