Binary Tree Maximum Path Sum 二叉树的最大路径和

来源:互联网 发布:小甲鱼python视频教程 编辑:程序博客网 时间:2024/05/16 05:28

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.

For example:
Given the below binary tree,

       1      / \     2   3

Return 6.

用递归实现这个代码非常简洁,易懂。

分析:现在的这个路径和,是一系列任意节点的和,只要这个路径上的相邻两个节点有parent-child连接就可以了。

我们要明白的一点是: 路径和一定是以某个节点node 为中间连接的路径。

又可以具体扩展:以节点node为中间连接的路径 =  当前的node.val + max(0, maxPath(node.left)) + max(0, maxPath(node.right))

加max是为了处理这类情况:

       1       / \     -2  -3
maxPath函数表示当前节点能够组成的最大 path sum,注意,不一定要到leaf node的。

运行时间:


代码:

    private int maxSum = Integer.MIN_VALUE;    public int maxPathSum(TreeNode root) {        doMaxPathSum(root);        return maxSum;    }    /**     *     * @param root     * @return return the max path sum of root,     */    private int doMaxPathSum(TreeNode root) {        if (root == null) {            return 0;        }        int left = doMaxPathSum(root.left);        int right = doMaxPathSum(root.right);        int curSum = root.val + Math.max(0, left) + Math.max(0, right);        maxSum = Math.max(curSum, maxSum);        // do not have to go to the leaf node.        return Math.max(Math.max(left, right) + root.val, root.val);    }

1 0
原创粉丝点击