首页 > 代码库 > 【LeetCode】Binary Tree Maximum Path Sum 解题报告

【LeetCode】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.

【解析】

题意:在二叉树中找一条路径,使得该路径的和最大。该路径可以从二叉树任何结点开始,也可以到任何结点结束。

思路:递归求一条经过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

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