2016年8月23日星期二

[LeetCode]#124 Binary Tree Maximum Path Sum


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    class Result {
        public int max; // max path not necessarily from current root to leaf
        public int maxPath; // max path from current root to leaf node
        
        public Result(int max, int maxPath) {
            this.max = max;
            this.maxPath = maxPath;
        }
    }
    
    public int maxPathSum(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        Result result = getMaxPathSum(root);
        
        return result.max;
    }
    
    public Result getMaxPathSum(TreeNode root) {
        if (root == null) {
            return new Result(Integer.MIN_VALUE, Integer.MIN_VALUE);
        }
        
        Result left = getMaxPathSum(root.left);
        Result right = getMaxPathSum(root.right);
        
        int maxPath = Math.max(0, Math.max(left.maxPath, right.maxPath)) + root.val;
        int maxChild = Math.max(left.max, right.max);
        int maxPassRoot = Math.max(0, left.maxPath) + Math.max(0, right.maxPath) + root.val;
        
        int max = Math.max(maxPath, Math.max(maxChild, maxPassRoot));
        
        return new Result(max, maxPath);
        
    }
}


没有评论:

发表评论