Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.

For example:
Given the below binary tree,

       1
/ \
2 3

Return 6.

求最大路径。

就是记录两个结果。

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxPathSum(TreeNode root) {
if( root == null)
return 0;
long result[] = helper(root); return (int)Math.max(result[0], result[1]);
} public long[] helper(TreeNode node){
long[] result = new long[2];
result[0] = Integer.MIN_VALUE;
result[1] = Integer.MIN_VALUE;
if( node == null )
return result;
result[0] = node.val;
result[1] = node.val;
if( node.left == null && node.right == null)
return result; long[] num1 = helper(node.left);
long[] num2 = helper(node.right); result[0] = Math.max(Math.max(num1[0],num2[0])+node.val,node.val);
result[1] = Math.max(Math.max(Math.max(Math.max(Math.max(num1[1],num2[1]),num1[0]+num2[0]+node.val),num1[0]+node.val),
num2[0]+node.val),node.val); return result;
}
}

最新文章

  1. UIPIckerView现实城市选择
  2. windows下安装Apache 64bit
  3. spring mvc 注解 学习笔记(一)
  4. activity 和 生命周期: 消息通信
  5. leveldb - menifest文件格式
  6. javascript 通过IE ActiveX 获得本机内网ip
  7. 在html页头设置不缓存
  8. CF 552C 进制转换
  9. 【Android界面实现】可旋转的汽车3D模型效果的实现
  10. 个人作业2——英语学习APP案例分析
  11. mysql 优化方法
  12. SpringMvc4.x---快捷的ViewController
  13. Codeforces Round #396(Div. 2) A. Mahmoud and Longest Uncommon Subsequence
  14. Mysql 导入文件提示 --secure-file-priv option 问题
  15. pl/sql报错快速解决方法(新手推荐)
  16. JMeter java.net.URISyntaxException:Illegalcharacterinquery解决方案
  17. 解决浏览器跨域限制方案之CORS
  18. ubuntu下安装搜狗输入法以及出现不能输入中文的解决办法
  19. javascript高级技巧篇(作用域安全、防篡改、惰性载入、节流、自定义事件,拖放)
  20. NET使用NPOI组件导出Excel-入门示例及通用方法

热门文章

  1. 【STL】-Map/Multimap的用法
  2. PL/SQL
  3. new 动态分配数组空间
  4. [转]AndroidManifest.xml文件详解
  5. Allow windows service to "Interact with desktop"
  6. python文件打包格式,pip包管理
  7. (转)js函数参数设置默认值
  8. hdu 2064
  9. postgreSQL9.1忘记postgres用户密码怎么办
  10. 简单实现web单点登录