题目

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;
         
     }

最新文章

  1. Shell碎碎念
  2. JMeter--二、在Windows环境上搭建wordpress
  3. Android中activity背景色的设置
  4. Play Framework 完整实现一个APP(三)
  5. codeforces 742E (二分图着色)
  6. IDA调试android so文件.init_array和JNI_OnLoad
  7. MVC4 使用 ckfinder+ckeditor编辑器
  8. css3中的动画处理
  9. 非常实用的15款开源PHP类库
  10. JQuery的Select操作集合
  11. 身为运维的你,怎么掌握python才不会失业
  12. 快速了解react
  13. 分析比较KafkaWordCount及DierctKafkaWordCount
  14. Delphi获取本机所有的IP
  15. .NET西安社区 [拥抱开源,又见 .NET] 活动简报
  16. Velodyne VLP-16 gmapping 建图
  17. curl: (25) Failed FTP upload: 550 解决方案
  18. 16.vue-cli跨域,swiper,移动端项目
  19. IO 流小记录
  20. python 修改excel

热门文章

  1. progress进度条的样式修改
  2. 每日踩坑 2018-01-09 WebAPI会如何面对URL中的空串string参数?
  3. hdu 4432 第37届ACM/ICPC天津现场赛B题
  4. Lvs+Keepalived+Mysql
  5. LINUX下动态链接库的使用-dlopen dlsym dlclose dlerror(转)
  6. perl解析xml-XML::Simple/XMLin
  7. ORA-00600: [kck_rls_check must use (11,0,0,0,0) or lower] 故障解决
  8. SystemParametersinfo的用法(一)
  9. 交叉编译gdb和gdbserver
  10. AngularJS路由系列(5)-- UI-Router的路由约束、Resolve属性、路由附加数据、路由进入退出事件