Binary Tree Maximum Path Sum


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]

      / \
     2   3

Output: 6

Example 2:

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

   / \
  9  20
    /  \
   15   7

Output: 42


We do a post order traversal and capture the max sum of all possible branches.

class Solution {
    public int maxPathSum(TreeNode root) {
        if(root==null) return 0;
        int max[] = new int[1];
        max[0] = Integer.MIN_VALUE;
        helper(root, max);
        return max[0];
    private int helper(TreeNode root, int[] max){
        if(root==null) return 0;
        int leftMax = Math.max(0, helper(root.left, max)); //avoids negative values
        int rightMax = Math.max(0, helper(root.right, max));
        max[0] = Math.max(max[0], root.val+leftMax+rightMax); //considers the whole branch
        // we already captured the current branch max, so we pick only left or right to make room for larger branches.
        return root.val+Math.max(leftMax, rightMax);