当前位置:网站首页>LeetCode:124. 二叉树中的最大路径和
LeetCode:124. 二叉树中的最大路径和
2022-07-06 08:44:00 【Bertil】
路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。
路径和 是路径中各节点值的总和。
给你一个二叉树的根节点 root ,返回其 最大路径和 。
示例 1:

输入:root = [1,2,3]
输出:6
解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6
示例 2:
输入:root = [-10,9,20,null,null,15,7]
输出:42
解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
提示:
- 树中节点数目范围是 [1, 3 * 10^4]
- -1000 <= Node.val <= 1000
解题思路
1.首先遍历左右子树的深度,当前节点往下走的最大值分三种情况:
- 往左走:当前节点+L(左子树的最大深度)
- 往右走:当前节点+R(右子树的最大深度)
- 不走:当前节点如果为负值,直接返回0
2.然后定义最大路径和ans为根节点+左子树+右子树的深度最大值
3.最后,递归完成后直接返回最大路径和ans即可
代码
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
/** * @param {TreeNode} root * @return {number} */
var maxPathSum = function(root) {
let ans = -9999;
dfs(root);
return ans;
// 从当前节点往下走
function dfs(root) {
if(!root) return 0;
// 遍历左子树的深度
let left = dfs(root.left);
// 遍历右子树的深度
let right = dfs(root.right);
// 更新路径的最大值
ans = Math.max(ans, root.val + left + right);
// 返回从当前节点往下走的最大值
return Math.max(0, Math.max(left, right) + root.val);
}
};
边栏推荐
猜你喜欢

704 二分查找

电脑清理,删除的系统文件

pytorch训练好的模型在加载和保存过程中的问题

Detailed explanation of heap sorting

sublime text没关闭其他运行就使用CTRL+b运行另外的程序问题

sublime text中conda环境中plt.show无法弹出显示图片的问题

Pointer advanced --- pointer array, array pointer

【刷题】牛客网面试必刷TOP101

C language double pointer -- classic question type

2022.02.13 - NC003. Design LRU cache structure
随机推荐
The mysqlbinlog command uses
优秀的软件测试人员,都具备这些能力
Unified ordering background interface product description Chinese garbled
按位逻辑运算符
ROS compilation calls the third-party dynamic library (xxx.so)
Generator parameters incoming parameters
Target detection - pytorch uses mobilenet series (V1, V2, V3) to build yolov4 target detection platform
Navicat Premium 创建MySql 创建存储过程
软件卸载时遇到trying to use is on a network resource that is unavailable
marathon-envs项目环境配置(强化学习模仿参考动作)
Research and investment forecast report of citronellol industry in China (2022 Edition)
Esp8266-rtos IOT development
China Light conveyor belt in-depth research and investment strategy report (2022 Edition)
Chrome浏览器的crash问题
POI add write excel file
Image,cv2读取图片的numpy数组的转换和尺寸resize变化
@JsonBackReference和@JsonManagedReference(解决对象中存在双向引用导致的无限递归)
sublime text没关闭其他运行就使用CTRL+b运行另外的程序问题
Detailed explanation of heap sorting
Rviz仿真时遇到机器人瞬间回到世界坐标原点的问题及可能原因