摘要:调用函数更新路径和的最大值,而函数本身需要递归,返回的是单边路径和。所以函数要返回的是,主函数中返回的却是最上一层根节点处和的较大值,与之前遍历过所有路径的最大值之间的最大值。
Problem
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
ExampleGiven the below binary tree:
</>复制代码
1
/
2 3
return 6.
Note调用helper函数更新路径和的最大值res,而helper函数本身需要递归,返回的是单边路径和single。这里需要注意:对于拱形路径和arch,从左子树经过根节点绕到右子树,路径已经确定,就不能再通过根节点向上求和了;对于单边路径和single,只是左边路径和left和右边路径和right的较大值与根节点的和,再与根节点本身相比的较大值,这个值还会递归到上一层继续求和。所以helper函数要返回的是single,主函数中返回的却是最上一层(根节点处)single和arch的较大值,与之前遍历过所有路径的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);
}
}
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/65852.html
摘要:解法真的非常巧妙,不过这道题里仍要注意两个细节。中,为时,返回长度为的空数组建立结果数组时,是包括根节点的情况,是不包含根节点的情况。而非按左右子树来进行划分的。 Problem The thief has found himself a new place for his thievery again. There is only one entrance to this area,...
摘要:复杂度思路对于每一节点,考虑到这一个节点为止,所能形成的最大值。,是经过这个节点为止的能形成的最大值的一条支路。 Leetcode[124] Binary Tree Maximum Path Sum Given a binary tree, find the maximum path sum. For this problem, a path is defined as any se...
摘要:但是本题的难点在于,使用递归实现,但是前面的第四种情况不能作为递归函数的返回值,所以我们需要定义两个值,代表单边路径的最大值,用于递归用于和回路的较大值。 Binary Tree Maximum Path SumGiven a binary tree, find the maximum path sum. For this problem, a path is defined as a...
摘要:栈迭代复杂度时间空间递归栈空间对于二叉树思路首先我们分析一下对于指定某个节点为根时,最大的路径和有可能是哪些情况。代码连接父节点的最大路径是一二四这三种情况的最大值当前节点的最大路径是一二三四这四种情况的最大值用当前最大来更新全局最大 Binary Tree Maximum Path Sum Given a binary tree, find the maximum path sum...
摘要:题目描述举例题目分析找从任意节点出发的任意路径的最大长度。每个都有可能是其他路径上的,这种情况要,。每个都有可能作为中心,此时要左侧之前的路径最长长度,左侧之前的路径最长长度,此为中心时候的长度将这个分析单元递归封装,即可实现目标。 题目描述: Given a binary tree, find the maximum path sum. For this problem, a p...
阅读 4499·2021-11-24 10:24
阅读 1456·2021-11-22 15:22
阅读 2116·2021-11-17 09:33
阅读 2510·2021-09-22 15:29
阅读 553·2019-08-30 15:55
阅读 1699·2019-08-29 18:42
阅读 2772·2019-08-29 12:55
阅读 1814·2019-08-26 13:55
极致性价比!云服务器续费无忧!
Tesla A100/A800、Tesla V100S等多种GPU云主机特惠2折起,不限台数,续费同价。
NVIDIA RTX 40系,高性价比推理显卡,满足AI应用场景需要。
乌兰察布+上海青浦,满足东推西训AI场景需要