您的位置:首页 > 其它

124. Binary Tree Maximum Path Sum

2015-08-13 16:40 441 查看
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.
9.15更新
----------
注意此题,是一道很有意思,并且很trick的题目。因为最大值的起始端和末尾端可能是在root的某棵子树上,所以用递归的方式来求最大值是不可行的。那么怎么办呢,这道题明显还是一道递归题啊,解决办法就是把ret作为引用传下去,这样就能自底向上地求得最大值。另外需要注意一点,递归函数的返回值,在这里需要特别注意,函数返回值是root作为端点的最大值(这里root作为端点分为三种情况,1.只有root
2.root和左子树, 3.root和右子树)。为什么要让函数的返回值是这个呢,因为递归函数返回的值,应该与root的父亲可以连接起来,否则就不能与root的父亲一起构成可能更大的数值,而且在逻辑上也说不通。


算法:

arch代表穿过当前节点的路径(左边一支儿+自己节点+右边一支儿)。
注意树的节点可以是负数,所以arch不一定是最长的。
每次return以root(当前节点)开头最大的单只path sum。
update res[0],用arch和以自己开头一支儿的比,谁大就把res[0] update成谁。

public int maxPathSum(TreeNode root) {    int[] res = new int[1];    res[0] = Integer.MIN_VALUE;    maxPath(root, res);    return res[0];}private int maxPath(TreeNode root, int[] res) {    if (root == null)        return 0;    int left = maxPath(root.left, res);//左边一支儿(不算自己)    int right = maxPath(root.right, res);    int arch = left + right + root.val; //穿过自己    int single = Math.max(root.val, Math.max(left, right) + root.val);(算上自己)    res[0] = Math.max(res[0], Math.max(arch, single));//update结果    return single;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: