当前位置:网站首页>二叉树中最大路径和[处理好任意一颗子树,就处理好了整个树]
二叉树中最大路径和[处理好任意一颗子树,就处理好了整个树]
2022-06-24 13:00:00 【REN_林森】
前言
对于二叉树而言,利用好本身的递归体质,是解决问题的关键,处理好递归中任意一棵子树,就处理好了整个树。通过二叉树中最大路径和练习回溯+处理子树。
一、二叉树中最大路径和


二、回溯+处理子树
package everyday.hard;
// 二叉树中的最大路径和。
public class MaxPathSum {
/* target:找到任意路径和最大的值。 从递归结构来看的话,左右子树想要有路径,那必然只能在左右子树选一个孩子,通过父节点连通。 而要选最大和的路径值,可用一个变量记录max即可。 */
public int maxPathSum(TreeNode root) {
// 在遍历过程中寻找最大值。
order(root);
// 返回寻找到的最大值。
return max;
}
private int max = 1 << 31;
private int order(TreeNode root) {
// 访问到null节点,递归结束,返回贡献值0.
if (null == root) return 0;
// 回溯得到 左右值。
int left = order(root.left);
int right = order(root.right);
// 四种可选路径,左根 | 右根 | 根 | 左根右
// 返回的路径和只能在前三种中选最大值,而max化,需要在四种路径中取最大值。
// 先找前三者谁大,谁大,返回谁;再和左根右比较,跟max比较,得到max.
int rs = Math.max(left + root.val, Math.max(right + root.val, root.val));
// 更新max
max = Math.max(max, Math.max(rs, left + right + root.val));
// 返回最大子路径和
return rs;
}
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}
总结
1)处理好每一颗子树。
2)二叉树处理问题,要么从上到下,要么从下往上看问题。
参考文献
边栏推荐
- Jerry's serial port receiving IO needs to set the digital function [chapter]
- 位于相同的分布式端口组但不同主机上的虚拟机无法互相通信
- Gatling 性能测试
- Kotlin anonymous function and lambda
- The real project managers are all closed-loop masters!
- JS remove string spaces
- [5g NR] 5g NR system architecture
- 杰理之串口接收 IO 需要设置数字功能【篇】
- 2022煤矿瓦斯抽采操作证考试题及模拟考试
- HarmonyOS-3
猜你喜欢

一键生成大学、专业甚至录取概率,AI填报志愿卡这么神奇?

Mit-6.824-lab4a-2022 (ten thousand words explanation - code construction)

markdown/LaTeX中在字母下方输入圆点的方法

快手实时数仓保障体系研发实践

居家办公更要高效-自动化办公完美提升摸鱼时间 | 社区征文

智慧园区SaaS管理系统解决方案:赋能园区实现信息化、数字化管理

万用表测量电阻图解及使用注意事项

如何在物联网低代码平台中进行任务管理?

win10系统问题

2022 Quality Officer - Equipment direction - post skills (Quality Officer) recurrent training question bank and online simulation examination
随机推荐
Jerrys timer0 uses the default pa13 to detect the pulse width [chapter]
HarmonyOS-3
图扑软件数字孪生海上风电 | 向海图强,奋楫争先
4个不可不知的“安全左移”的理由
一键生成大学、专业甚至录取概率,AI填报志愿卡这么神奇?
杰理之串口接收 IO 需要设置数字功能【篇】
OpenHarmony 1
杰理之红外滤波【篇】
杰理之无缝循环播放【篇】
Docker安装redis
OpenHarmony 1
2022 coal mine gas drainage operation certificate examination questions and simulation examination
2022 construction elevator driver (construction special type of work) examination questions and online simulation examination
初识云原生安全:云时代的最佳保障
Seven challenges faced by data scientists and Solutions
4 reasons for "safe left shift"
These default routes and static routes can not be configured and deployed. What kind of network workers are they!
2022年氟化工艺考试模拟100题及答案
Usage of multimeter
数商云:加强供应商管理,助推航空运输企业与供应商高效协同