[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.

https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/

 

思路:因为树节点的值有可能是负值,所以并不一定长度越长总和就越大。递归求解,对于当前节点,递归求出左右子树的最大和,然后在root.val, root.val + leftSum, root.val + rightSum, root.val + leftSum + rightSum四种情况下找出最大的更新max值,注意返回时必须包括root节点和其中一个子节点用于父节点组成路径,所以是在root.val, root.val + leftSum, root.val + rightSum中选取最大的返回。

 

public class Solution {

    private int max = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        maxPath(root);
        return max;
    }

    private int maxPath(TreeNode root) {
        if (root == null)
            return 0;
        int leftSum = maxPath(root.left);
        int rightSum = maxPath(root.right);
        max = myMax(max, myMax(root.val, root.val + leftSum, root.val + rightSum, root.val + leftSum + rightSum));

        return myMax(root.val, root.val + leftSum, root.val + rightSum);

    }

    private int myMax(int... a) {
        int res = Integer.MIN_VALUE;
        for (int each : a) {
            if (each > res)
                res = each;
        }
        return res;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(1);
        root.right = new TreeNode(2);
        root.left.left = new TreeNode(3);
        root.left.right = new TreeNode(4);
        System.out.println(new Solution().maxPathSum(root));
    }

}

 

思路:如果左子树或者右子树返回值<0,我们用0代替。

public class Solution {
    int maxValue;
    
    public int maxPathSum(TreeNode root) {
        maxValue = Integer.MIN_VALUE;
        maxPathDown(root);
        return maxValue;
    }
    
    private int maxPathDown(TreeNode node) {
        if (node == null) return 0;
        int left = Math.max(0, maxPathDown(node.left));
        int right = Math.max(0, maxPathDown(node.right));
        maxValue = Math.max(maxValue, left + right + node.val);
        return Math.max(left, right) + node.val;
    }
}

 

 

第三遍记录:

思路不变,每次更新max的时候,max本身不要忘记了。 

posted @ 2014-07-03 21:42  jdflyfly  阅读(154)  评论(0编辑  收藏  举报