Binary Tree Maximum Path Sum leetcode java
2024-10-21 03:51:32
题目:
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
Return 6
.
题解:
递归求解。
取当前点和左右边加和,当前点的值中最大的作为本层返回值。并在全局维护一个max。使用数组,因为是引用类型。所以在递归过程中可以保存结果。
代码如下:
1 public int maxPathSum(TreeNode root) {
2 int[] max = new int[1];
3 max[0] = Integer.MIN_VALUE;
4 findmax(root,max);
5 return max[0];
6 }
7
8 public int findmax(TreeNode root, int[] max){
9 if(root==null)
return 0;
int left = findmax(root.left,max);
int right = findmax(root.right,max);
int ans = Math.max(root.val,Math.max(root.val+left, root.val+right));
max[0] = Math.max(max[0],Math.max(ans,root.val+left+right));
return ans;
}
最新文章
- Shell碎碎念
- JMeter--二、在Windows环境上搭建wordpress
- Android中activity背景色的设置
- Play Framework 完整实现一个APP(三)
- codeforces 742E (二分图着色)
- IDA调试android so文件.init_array和JNI_OnLoad
- MVC4 使用 ckfinder+ckeditor编辑器
- css3中的动画处理
- 非常实用的15款开源PHP类库
- JQuery的Select操作集合
- 身为运维的你,怎么掌握python才不会失业
- 快速了解react
- 分析比较KafkaWordCount及DierctKafkaWordCount
- Delphi获取本机所有的IP
- .NET西安社区 [拥抱开源,又见 .NET] 活动简报
- Velodyne VLP-16 gmapping 建图
- curl: (25) Failed FTP upload: 550 解决方案
- 16.vue-cli跨域,swiper,移动端项目
- IO 流小记录
- python 修改excel
热门文章
- progress进度条的样式修改
- 每日踩坑 2018-01-09 WebAPI会如何面对URL中的空串string参数?
- hdu 4432 第37届ACM/ICPC天津现场赛B题
- Lvs+Keepalived+Mysql
- LINUX下动态链接库的使用-dlopen dlsym dlclose dlerror(转)
- perl解析xml-XML::Simple/XMLin
- ORA-00600: [kck_rls_check must use (11,0,0,0,0) or lower] 故障解决
- SystemParametersinfo的用法(一)
- 交叉编译gdb和gdbserver
- AngularJS路由系列(5)-- UI-Router的路由约束、Resolve属性、路由附加数据、路由进入退出事件