您的位置:首页 > 其它

【LeetCode】Binary Tree Maximum Path Sum 解题报告

2015-01-22 16:15 363 查看
【题目】

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
.
【解析】
题意:在二叉树中找一条路径,使得该路径的和最大。该路径可以从二叉树任何结点开始,也可以到任何结点结束。

思路:递归求一条经过root的最大路径,这条路径可能是:

1) 左边某条路径 + root + 右边某条路径

2) 左边某条路径 + root

3) root + 右边某条路径

4) root

【Java代码】

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private int max = Integer.MIN_VALUE;
    
    public int maxPathSum(TreeNode root) {
        if (root == null) return 0;
        
        maxSum(root);
        
        return max;
    }
    
    public int maxSum(TreeNode root) {
        if (root == null) return 0;
        
        int leftVal = maxSum(root.left);    //递归求左支路的最大路径和
        int rightVal = maxSum(root.right);  //递归求右支路的最大路径和
        
        //如果当前局部解(root或left+root或root+right或left+root+right)是最有解,更新最终结果
        int curMax = root.val;
        if (leftVal > 0) {
            curMax += leftVal;
        }
        if (rightVal > 0) {
            curMax += rightVal;
        }
        if (curMax > max) {
            max = curMax;
        }
        
        //返回从叶子结点到root的最大路径和(root或left+root或root+right)
        return Math.max(root.val, Math.max(root.val + leftVal, root.val + rightVal));
    }
}


参考:http://blog.csdn.net/worldwindjp/article/details/18953987
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: