124. Binary Tree Maximum Path Sum
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int maxValue = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
recursion(root);
return maxValue;
}
// returns the max value from current node to left or right
private int recursion(TreeNode node){
if(node == null) return 0;
int left = Math.max(0, recursion(node.left));
int right = Math.max(0,recursion(node.right));
// check if the path value from let to node to right is larger than maxValue
maxValue=Math.max(maxValue, node.val + left + right);
return node.val+Math.max(left, right);
}
}
Last updated
Was this helpful?