Unnikrishnan
1 min readApr 19, 2020

--

LeetCode Java Solutions

124. Binary Tree Maximum Path Sum

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:

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

Solution

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int maxPathSum = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
pathSum(root);
return maxPathSum;
}
private int pathSum(TreeNode node){
if(node == null){
return 0;
}
int left = Math.max(0, pathSum(node.left));
int right = Math.max(0, pathSum(node.right));
maxPathSum = Math.max(maxPathSum, left+right+node.val);
return Math.max(left,right)+node.val;
}
}

--

--

Unnikrishnan

Software Engineer from Silicon Valley, having more than 10 years of experience in Software Development,Data Engineering, Data Modeling etc