[LintCode/LeetCode] Binary Tree Maximum Path Sum

395 查看

Problem

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

Example

Given the below binary tree:

  1
 / \
2   3

return 6.

Note

调用helper函数更新路径和的最大值res,而helper函数本身需要递归,返回的是单边路径和single。这里需要注意:对于拱形路径和arch,从左子树经过根节点绕到右子树,路径已经确定,就不能再通过根节点向上求和了;对于单边路径和single,只是左边路径和left和右边路径和right的较大值与根节点的和,再与根节点本身相比的较大值,这个值还会递归到上一层继续求和。所以helper函数要返回的是single,主函数中返回的却是最上一层(根节点处)singlearch的较大值,与之前遍历过所有路径的res最大值之间的最大值。

Solution

public class Solution {
    int res = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        helper(root);
        return res;
    }
    public int helper(TreeNode root) {
        if (root == null) return 0;
        int left = helper(root.left);
        int right = helper(root.right);
        int arch = left+right+root.val;
        int single = Math.max(Math.max(left, right)+root.val, root.val);
        res = Math.max(res, Math.max(single, arch));
        return single;
    }
}

Simplified

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