1. 程式人生 > >leetcode-124:Binary Tree Maximum Path Sum(Java)

leetcode-124:Binary Tree Maximum Path Sum(Java)

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,

要求:計算二叉樹中的路徑之和最大值,起止節點為任意

解法:動態規劃,對每一個節點,以該節點為根節點的最大值設為value,其左子樹的路徑最大值為lmax,右子樹的路徑最大值為rmax,(!!! 注意:這裡的lmax和rmax指的是從左/右子節點出發的某一條單向路徑,例如對於節點4,lmax=2+3 rmax=6+7+8,而並不是lmax=1+2+3 rmax=5+6+7+8)那麼有:

value = value + (lmax>0?lmax:0) + (rmax>0?rmax:0) ;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.math.*;
public class Solution {
    int maxSum = Integer.MIN_VALUE;
    
    public int maxPathSum(TreeNode root) {
        if(root == null)
            return 0;
            
        getMaxSumWithCurNode(root);
        return maxSum;
    }
    
    
    int getMaxSumWithCurNode(TreeNode curNode){
        int lmax = 0, rmax = 0;
        int value = curNode.val; // 包含當前節點的最大路徑和
        if(curNode.left != null){
            lmax = getMaxSumWithCurNode(curNode.left);
        }
        if(curNode.right != null){
            rmax = getMaxSumWithCurNode(curNode.right);
        }
        
        value = value + (lmax>0?lmax:0) + (rmax>0?rmax:0) ;
        if(value > maxSum)
            maxSum = value;
        // 注意這裡的返回值,取左右子樹其中一條路徑    
        return curNode.val+Math.max( lmax>0?lmax:0, rmax>0?rmax:0 );
        
    }
}