TODO: 124. Binary Tree Maximum Path Sum
#dfs #tree
Problem
Intuition



Time Complexity
Space Complexity
Solution
Last updated
#dfs #tree



Last updated
/**
* 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 maxSum = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
// TC: O(n), traversing every node once
// SC: O(h), height of the stack
if(root == null) {
return 0;
}
getPathSum(root);
return maxSum;
}
private int getPathSum(TreeNode node) {
if(node == null) return 0;
// Pick the max of 0 or pathsum. We are using 0 because, if already a negative
// value is present, then adding to current value only makes the value lower
int leftPathSum = Math.max(0, getPathSum(node.left));
int rightPathSum = Math.max(0, getPathSum(node.right));
// In case, if negative value is the highest path sum, it is compared to maxSum
// so negative values are also not missed
// Take the total sum value of the path
int currSum = leftPathSum + node.val + rightPathSum;
maxSum = Math.max(maxSum, currSum); // Keep comparing to maxSum at every iteration
// The reason we are choosing max of leftPathSum or rightPathSum is, according
// to the question, we need to pick a path which maximises the sum
return node.val + Math.max(leftPathSum, rightPathSum);
}
}