L124. Binary Tree Maximum Path Sum

Problem:

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  2+1+3

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42  15+ 20 + 7

Solution:

  • take max among left path, right path, full path, or root value

  • temp Max is the max from left branch and right branch

  • cur Max is from root.val and tempMax

  • max[0] is for keep the global max from either curMax or history max

  • only can return curMax since we can't re use branches

public int maxPathSum(TreeNode root) {
    if(root == null) return 0;
    int[] max = new int[]{Integer.MIN_VALUE};
    pathSum(root, max);
    return max[0];
}
public int pathSum(TreeNode root, int[] max){
    if(root == null) return 0;
    int leftSum = pathSum(root.left, max);
    int rightSum = pathSum(root.right, max);
    // 
    int tempMax = Math.max(leftSum + root.val, rightSum + root.val);
    int curMax = Math.max(tempMax,root.val);
    max[0] = Math.max(max[0], Math.max(curMax, leftSum + rightSum + root.val));
    return curMax;
}

Last updated

Was this helpful?