Description
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
Example 1:
Input: [1,2,3]
1
/ \
2 3
Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
Output: 42
Solving
The result is recorded by a global variable, in order to get both every node’s maximum side(left or right) sum and the maximum path sum by a recursion. The return value of recursion is the maximum side sum of this node.
/**
* 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) {
getMaxPathSum(root);
return res;
}
private int getMaxPathSum(TreeNode node) {
if (node == null)
return 0;
int left = Math.max(0, getMaxPathSum(node.left));
int right = Math.max(0, getMaxPathSum(node.right));
res = Math.max(left + right + node.val, res);
return Math.max(left, right) + node.val;
}
}