Question
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 4
/ \
2 3
The highlighted path yields the maximum sum 10.
https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/
*Difficulty: Hard, Frequency: Medium
Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int maxSum;
public int maxPathSum(TreeNode root) {
maxSum = Integer.MIN_VALUE;
findMax(root);
return maxSum;
}
public int findMax(TreeNode node){
if(node == null) return 0;
int left = findMax(node.left);
int right = findMax(node.right);
maxSum = Math.max(node.val+left+right, maxSum);
int ret = Math.max(right, left) + node.val;
return ret > 0 ? ret : 0;
}
}