Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1
      / \
     2   3

Return 6.


Analysis: For each node, there are total four possible ways to generate the max path sum. 

a. The node itself. 

b. The node itself plus left subtree. 

c. The node itself plus right subtree. 

d. The node itself plus left and right subtrees. 

For each node, we should find the maximum value in these four cases and then compare with the current maximum value and update if necessary. Keep in mind that case d cannot be passed to the upper level node since it does not a qualified path. Therefore, we should find the maximum value among a, b and c and then return it back to the upper level node. 

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxPathSum(TreeNode root, int[] maxSum) {
        if(root==null) return 0;
        int leftSum = root.val+maxPathSum(root.left, maxSum);       // root + left subtree
        int rightSum = root.val+maxPathSum(root.right, maxSum);     // root + right subtree
        int totalSum = leftSum+rightSum-root.val;                   // root + left subtree + right subtree
        int nextMaxSum = Math.max(root.val, Math.max(leftSum, rightSum));   // max{left, right, self}
        int localMaxSum = Math.max(totalSum, nextMaxSum);   // max{across, left, right, self}
        if(localMaxSum>maxSum[0]) maxSum[0]=localMaxSum;
        return nextMaxSum;
    }
    
    public int maxPathSum(TreeNode root) {
        int[] maxSum = new int[1];
        maxSum[0] = Integer.MIN_VALUE;
        maxPathSum(root, maxSum);
        return maxSum[0];
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章