LeetCode_124 Binary Tree Maximum Path Sum
2015-07-30 11:33
471 查看
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,
Return 6.
如果这个作为root,那么最长路应该就是F(left) + F(right) + val.当然如果left,或者right<0就不用加了
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6.
如果这个作为root,那么最长路应该就是F(left) + F(right) + val.当然如果left,或者right<0就不用加了
int max = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { if(root == null) return 0; maxSum(root); return max; } private int maxSum(TreeNode root){ if(root == null) return 0; int value = root.val; int lmax = 0; int rmax = 0; if(root.left !=null){ lmax = maxSum(root.left); if(lmax > 0){ value +=lmax; } } if(root.right != null){ rmax = maxSum(root.right); if(rmax > 0){ value +=rmax; } } if(value > max){ max = value; } return Math.max(root.val, Math.max(root.val+lmax, root.val+rmax)); }
相关文章推荐
- HDOJ 2199 Can you solve this equation?(二分查找)
- Matlab--统计图的绘制
- UIKit 视图的生命周期
- EJB学习(四)——Enterprise Bean(企业Bean)和Entity Bean(实体Bean)
- 文件访问权限
- 搞个这样的APP要多久?
- jquery 获取url地址参数
- VMWare虚拟机迁移时,打开后提示主机不支持 CPUID 错误
- js 根据年月获取当月有多少天_js获取农历日期_及Js其它常用有用函数
- hdu 2199~Can you solve the equation?~二分法求解
- 自动释放池autoreleasepool
- django 设置 数据库缓存
- 一道简单的计算题,真正能懂的投资者不多
- web.xml
- Windows下DC、openGL、 RC关系
- 生产者消费者问题
- tomcat服务器相关配置
- android ListView详解
- Hibernate 级联删除失败问题
- hadoop streaming 输出数据分割与二次排序