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

思路:

这道题目很难…题目要求求最大路径和,但是注意到路径开始节点和结束节点是任意的。查了很多的博客,对这道题目终于有了一些理解。
1.路径有4种情况:
(1)左子树的路径加上当前节点;
(2)右子树的路径加上当前节点;
(3)左右子树的路径加上当前节点(相当于一条横跨当前节点的路径);
(4)只有自己的路径。
2.从而可以将path归纳为两种情况:
(1) root->leaf path中的一段:即题目例子中的1-2或1-3。
(2) 两个节点之间经过它们lowest common ancestor (LCA)的path:即题目中的2-1-3。

  1. 显然top-down的递归并不适用于这题,因为对于类型(2)的path,它的path sum同时取决于LCA左右sub path的最大值。而这样的path sum是无法通过top-down传递来获取的。

  2. 所以这里可以采用bottom-up的递归方法:
    对于节点x:
    定义PS1(x)为从x出发向leaf方向的第一类path中最大的path sum。
    定义PS2(x)为以x为LCA的第二类path中的最大path sum。
    显然如果我们求得所有节点x的PS1 & PS2,其中的最大值必然就是要求的max path sum。

  3. 如何求PS1(x)、PS2(x)?
    (1) PS1(x) 、PS2(x)至少应该不小于x->val,因为x自己就可以作为一个单节点path。
    (2) PS1(x) 、 PS2(x)可以从PS1(x->left)和PS1(x->right)来求得:
    PS1(x) = max [ max(PS1(x->left), 0), max(PS1(x->right), 0) ] + x->val
    PS2(x) = max(PS1(x->left), 0) + max(PS1(x->right), 0) + x->val
    注意这里并不需要PS2(x->left) 以及 PS2(x->right) 因为子节点的2型path无法和父节点构成新的path。

  4. 需要返回PS1(x)以供上层的节点计算其PS1 & PS2.

  5. 对于leaf节点:PS1(x) = PS2(x) = x->val.

java实现

public class Solution7 {

    private int max = Integer.MIN_VALUE;// 保存全局最大值

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

    public int findMaxPathSum(TreeNode root) {
        if (root == null)
            return 0;
        int left = findMaxPathSum(root.left);
        int right = findMaxPathSum(root.right);
        //计算PSI(X)
        int currSum = Math.max(Math.max(left + root.val, right + root.val), root.val);
        //计算PS2(X)
        int currMax = Math.max(currSum, left + root.val + right);
        max = Math.max(max, currMax);
        return currSum;
    }
}

感谢
(http://www.cnblogs.com/grandyang/p/4280120.html)
(http://bangbingsyb.blogspot.tw/2014/11/leetcode-binary-tree-maximum-path-sum.html)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值