当前位置:网站首页>高频leetcode深搜部分:124. 二叉树中的最大路径和
高频leetcode深搜部分:124. 二叉树中的最大路径和
2022-07-21 17:53:00 【嗝~~~~】
124. 二叉树中的最大路径和
难度困难1426
路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。
路径和 是路径中各节点值的总和。
给你一个二叉树的根节点 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 * 104]
- -1000 <= Node.val <= 1000
思路
- 失败思路:中序遍历,设置全局变量,遍历时累加(没有考虑路径选择:向上还是向右)
代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class Solution {
private:
int maxSum = INT_MIN;
public:
int maxGain(TreeNode* node) {
if (node == nullptr) {
return 0;
}
// 递归计算左右子节点的最大贡献值
// 只有在最大贡献值大于 0 时,才会选取对应子节点
int leftGain = max(maxGain(node->left), 0);
int rightGain = max(maxGain(node->right), 0);
// 节点的最大路径和取决于该节点的值与该节点的左右子节点的最大贡献值(左中右)
int priceNewpath = node->val + leftGain + rightGain;
// 更新答案
maxSum = max(maxSum, priceNewpath);
// 返回节点的最大贡献值,(继续向父节点找)
return node->val + max(leftGain, rightGain);
}
int maxPathSum(TreeNode* root) {
maxGain(root);
return maxSum;
}
};
边栏推荐
- 分省市县地理空间矩阵:地级市空间、地理距离矩阵等多指标数据集
- 异常类
- Good wheel collection: an image loading library STB that supports almost all popular formats_ image. h
- SerializationException: Could not read JSON: Unrecognized token “xxx“
- OpenGL: dynamically modify vbo/ebo
- 1978-2021中国统计年鉴、2003-2019(省、市面板数据)、1999-2019(县域面板数据)
- Use of laravel correlation model, one to one, one to many, many to many
- Docker series VI Docker installation redis
- Collection集合框架
- Analysis of copyonwritearraylist
猜你喜欢
How to quickly develop a simple and practical MES system?
Array of C language
The pit trodden by real people tells you to avoid the 10 mistakes that novices in automated testing often make
c语言之指针(三)
Literature: case "film ranking"
写了2个月的借贷系统的心得
跨境贸易术语
About the plaintext syntax of vditor Publishing
4000+上市公司所属省份、城市、经营等多指标数据已更新至2022.1
SerializationException: Could not read JSON: Unrecognized token “xxx“
随机推荐
c语言之数组
Thread多线程
MySQL学习之MVCC多版本并发控制
hdparm
Docker series VI Docker installation redis
Go zero micro service practical series (III. API definition and table structure design)
SQL 中delete与truncate的区别
Tencent cloud free upgrade.
conda 常用功能记录
Tool classes encapsulated based on redistemplate
1989-2020年学历结构和计算平均受教育年限数据
异常处理
两个栈实现一个队列
Pointer of C language (2)
LeetCode342:4的幂
华泰扫码开户安全吗?怎么开低佣金账户
Educational structure and calculated average years of education from 1989 to 2020
VSCODE配置Markdown,以及Markdown基础语法
Laravel installs the debugbar toolbar and configures the virtual host
如何快速开发一个简单实用的MES系统?