当前位置

网站首页> 程序设计 > 开源项目 > 程序开发 > 浏览文章

[LeetCode]Binary Tree Maximum Path Sum - EpoTalk

作者:小梦 来源: 网络 时间: 2024-02-05 阅读:

Binary Tree Maximum Path Sum

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.

分析

这道题开始我们要明白符合题目要求的路径有什么特点,要求是树种任意两个点即可,不一定要经过树的root, 路径的顺序必须是正常父子顺序。所以会发现,对任意一条路径,必然会有自己的root, 所以我们只要找出以每个node为root的路径的最大值,然后维护一个全局最大值,找的过程中不断更新全局最大值即可。

接下来就要考虑对一个node而言怎么找出以其为root的路径最大值,方法很简单,找出以左边node向下的最大值加上以右边node向下的最大值再加上本身值即可,注意如果左右边值或为负数,会影响自己路径的最大值,放弃加。找到以自己为root的路径最大值后,与全局最大值比较即可。同时,也应该返回以自己为开头,向下的路径最大值,方法就是把取左右向下较大值加上自己本身值即可。

这道题也可以有个Follow up, 比如最大值路径的node不是父子关系,要求最大值路径上的node不可以相邻(Google面试题)

具体分析见下文

复杂度

time: O(n), space: O(h)

代码

public class Solution {    public int maxPathSum(TreeNode root) {        int[] max = {Integer.MIN_VALUE}; // 全局最大值        helper(root, max);        return max[0];    }        public int helper(TreeNode node, int[] max) {        if (node == null)return 0;    // 分别返回以左右子node为起始点的路径的最大值        int left = helper(node.left, max);        int right = helper(node.right, max);    // 加上自己本身值后,计算返回值及更新全局最大值      int leftMax = Math.max(0, left);        int rightMax = Math.max(0, right);        max[0] = Math.max(max[0], node.val + leftMax + rightMax);        return node.val + Math.max(leftMax, rightMax);    }}

Follow up

要求路径上的点不可以是父子关系,即不可以相连接。

比如:

      1     / \    2   3   / \  1   8

Return 11(8 + 3).

分析

方法其实与上一题是一样的,只不过我们需要考虑多一点情况,对于某一个node而言,会有两种情况来算以该点为root的路径最大值,一是最大值包含该点,二是最大值不包含该点。同样对于helper function返回值而言也是,不尽需要返回包含该点的最大值,也需要返回不包含该点向下的最大值,因为这两个值父节点都会需要用。所以我们需要把helper function改成返回两个值。

复杂度

time: O(n), space: O(1)

代码

public class Solution {    public int maxPathSum(TreeNode root) {        int[] max = {Integer.MIN_VALUE};        helper(root, max);        return max[0];    }    public int[] helper(TreeNode node, int[] max) {        // res[0]表示包含该点的向下路径最大值,res[1]表示不包含该点向下路径最大值        int[] res = new int[2];        if (node == null)return res;        int[] left = helper(node.left, max);        int[] right = helper(node.right, max);        int leftMax = 0;        int rightMax = 0;        // 包含本身node, 由于最大值路径node不能连接,不可使用left[0]及right[0]        leftMax = Math.max(leftMax, left[1]);        rightMax = Math.max(rightMax, right[1]);        max[0] = Math.max(max[0], node.val + leftMax + rightMax);        res[0] = node.val + Math.max(leftMax, rightMax);        // 不包含本身node, 左右向下路径无论包不包含左右子节点都可以需要考虑        leftMax = 0;        rightMax = 0;        leftMax = Math.max(leftMax, Math.max(left[0], left[1]));        rightMax = Math.max(rightMax, Math.max(right[0], right[1]));        max[0] = Math.max(max[0], leftMax + rightMax);        res[1] = Math.max(leftMax, rightMax);        return res;    }}

热点阅读

网友最爱