Binary Tree Maximum Path Sum ---lintcode
来源:互联网 发布:java自动装箱和拆箱 编辑:程序博客网 时间:2024/05/18 17:27
Description
Given a binary tree, find the maximum path sum.The path may start and end at any node in the tree.
给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)
分析
看到这个题目的第一眼,我想的是左边最大路径和加上右边的最大路径和然后加上根节点的值。但是是任意节点。。所以 也很有可能是只在左侧或右侧 也有可能只是根节点。
先考虑左边+右边+根节点这种情况*(这个容易点:利用递归):
public int maxPathSum(TreeNode root) { // write your code here if(root==null) return 0; max=root.val; //左边最大路径和 int left= helper(root.left); //右边最大路径和 int right= helper(root.right); return left+right+root.val; } public int helper(TreeNode root){ if(root==null) return 0; int left=helper(root.left); int right=helper(root.right); int curMax=Math.max(root.val,Math.max(left,right)+root.val); return curMax; }
万一只在左边或右边怎么办?所以这里要定义一个变量max,用来比较。
开始max为根节点的值。在左右分支的递归的过程中 发现某一条路径(可能为一个节点,也可能为一个节点加上其左右节点,也可能为一个节点加上左节点或右节点。)的和大于max的值时,更新max.
其实就是 在左右分支递归的时候 将左或右分支的某一节点当成根节点再递归。
如在对左分支递归时,将-20 当成根节点,找到最大路径。在对-20递归时,-20的右分支把-5当成根节点
在-5 为根节点时,最大路径值是-5. 所以更新max=-5. 此时curmax也为-5 返回给其父节点。在-5 的父节点-20 时,curMax是-20,而-5 > curMax和 三个节点值相加。所以max仍为-5. -10的右分支同理,curMax=-15。 在-10为根节点,左分支curmax=-20,右分支curMax=-15,则得到curmax=-10.而max=-5>-10仍为最大值。最后就可以得到max为最大路径和为-5。
int max; public int maxPathSum(TreeNode root) { // write your code here if(root==null) return 0; max=root.val; helper(root); return max; } public int helper(TreeNode root){ if(root==null) return 0; int left=helper(root.left); int right=helper(root.right); int curMax=Math.max(root.val,Math.max(left,right)+root.val); // max=Math.max(max,Math.max(curMax,left+right+root.val)); return curMax; }
- lintcode:Binary Tree Maximum Path Sum
- *[Lintcode]Binary Tree Maximum Path Sum
- [lintcode] Binary Tree Maximum Path Sum II
- Binary Tree Maximum Path Sum ---lintcode
- 20150708 lintcode 总结 Binary Tree Maximum Path Sum Show result *****
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- python pip 导出安装包
- 【stm32f103】TIMER基本定时功能的使用(寄存器版)
- JVM如何设置DNS缓存失效时间
- Java和Scala学习日记5
- 连通图遍历策略之广度优先搜索(C语言)
- Binary Tree Maximum Path Sum ---lintcode
- JDBC连接MySQL数据库——案例
- JS图片压缩上传处理
- Memcached,Redis,MongoDB,HBase比较
- Spring RESTful
- Win32开发:完整的开发流程
- D
- opencv二值化函数cvAdaptiveThreshold和cvThreshold
- .Net Core下通过Proxy 模式 使用 WCF