leetcode 124. binary tree maximum path sum

124. Binary Tree Maximum Path Sum

Difficulty:: Hard

Given a non-empty 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.

Example 1:

1
2
3
4
5
6
7
Input: [1,2,3]

1
/
2 3

Output: 6

Example 2:

1
2
3
4
5
6
7
8
9
Input: [-10,9,20,null,null,15,7]

-10
/
9 20
/
15 7

Output: 42

Solution

Language: Java

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 {
int max;
public int maxPathSum(TreeNode root) {
max = Integer.MIN_VALUE;
if (root == null) {
return 0;
}
helper(root);
return max;
}

// return max
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
int leftMax = Math.max(helper(root.left), 0);
int rightMax = Math.max(helper(root.right), 0);
int totalMax = leftMax + rightMax + root.val;
max = Math.max(totalMax, max);
return root.val + Math.max(leftMax, rightMax);
}
}