lintcode-medium-Binary Tree Maximum Path Sum
2016-03-15 06:29
274 查看
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
Given the below binary tree:
return
一个二叉树的最大量路径,分三种情况:
1. 在左子树
2. 在右子树
3. 包括root,左子树一部分和右子树一部分
所以需要定义一个类,用来记录不同的情况,一个int用来记录左子树/右子树的最大值,一个int用来记录任何情况下的最大值
The path may start and end at any node in the tree.
Given the below binary tree:
1 / \ 2 3
return
6.
一个二叉树的最大量路径,分三种情况:
1. 在左子树
2. 在右子树
3. 包括root,左子树一部分和右子树一部分
所以需要定义一个类,用来记录不同的情况,一个int用来记录左子树/右子树的最大值,一个int用来记录任何情况下的最大值
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: An integer. */ class ResultType{ int singlePath; int maxPath; public ResultType(int singlePath, int maxPath){ this.singlePath = singlePath; this.maxPath = maxPath; } } public ResultType helper(TreeNode root){ if(root == null){ return new ResultType(0, Integer.MIN_VALUE); } ResultType left = helper(root.left); ResultType right = helper(root.right); int singlePath = Math.max(left.singlePath, right.singlePath) + root.val; singlePath = Math.max(0, singlePath); int maxPath = Math.max(left.maxPath, right.maxPath); maxPath = Math.max(maxPath, left.singlePath + right.singlePath + root.val); return new ResultType(singlePath, maxPath); } public int maxPathSum(TreeNode root) { // write your code here return helper(root).maxPath; } }
相关文章推荐
- python利用or在列表解析中调用多个函数.py
- 关于波峰波谷趋势分割(想象中的方法),判断趋势,突然来想到的,记下来,没有实验。以便以后用于分割
- 第22课:RDD的依赖关系彻底解密
- EditText 输入值限定最小值和最大值
- jsp页面获取后台数据
- C#
- 在OpenWRT上部署DNS服务器以方便访问谷歌
- 图像相似度计算之哈希值方法OpenCV实现
- 基于CUDA的粒子系统的实现
- 10.13 编程练习
- *循环单链表[不带头结点]
- 关于多人合作的经验
- composer安装过程超时的问题以及解决方案
- JAVA深复制(深克隆)与浅复制(浅克隆)
- 大话说github for windows的分支开发与合并(2n1)
- C语言实现单链表
- 用GCD线程组与GCD信号量将异步线程转换为同步线程
- 模糊数学课件(清晰易懂)
- [Getting and Cleaning data] Week 3
- [RxJS] Error Handling in RxJS