binary-tree-maximum-path-sum leetcode C++
2024-09-06 22:29:37
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example: Given the below binary tree,
1
/ \
2 3
Return6.
C++
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
int maxDis;
public:
int maxPathSum(TreeNode *root) {
if(!root){
maxDis=0;
return -1e8;
}
int leftMax=maxPathSum(root->left);
int l=max(0,maxDis);
int rightMax=maxPathSum(root->right);
int r=max(0,maxDis);
maxDis=max(l,r)+root->val;
return max(leftMax,max(rightMax,l+r+root->val));
}
};
最新文章
- JS 前端格式化JSON字符串工具
- hdu.1111.Secret Code(dfs + 秦九韶算法)
- IBindCtx接口定义
- java语言中数值自动转换的优先顺序
- shell script 的追踪与 debug
- Anti-Grain Geometry 概述
- Oracle GoldenGate中HANDLECOLLISIONS参数使用详解
- 怎么选择公司???MVC加jquery-easyui 后端工程师
- SpringBoot整合Swagger2,再也不用维护接口文档了!
- 总结,为什么要重写hashset的hashcode()和equals()?
- exec 命令简单用法 和 find 搭配用法示例
- B. Switches and Lamps
- bat 命令 常用配置及其用法
- [LintCode] Permutations
- dbms_stats.gather_table_stats详解
- 【MVC】Controller的使用
- unity灯光烘焙设置详解
- ubuntu 关闭和开启防火墙
- 关于webWorker的理解和简单例子
- CSDN日报20170401 ——《假设你还是“程序猿”,我劝你别创业!》