题目:二叉树中的最大路径和
来源:互联网 发布:淘宝宝贝关联阿里巴巴 编辑:程序博客网 时间:2024/05/21 19:28
给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)
您在真实的面试中是否遇到过这个题?
Yes
样例
给出一棵二叉树:
1
/ \
2 3
返回 6
标签 Expand
相关题目 Expand
您在真实的面试中是否遇到过这个题?
Yes
样例
给出一棵二叉树:
1
/ \
2 3
返回 6
标签 Expand
相关题目 Expand
解题思路:
二叉树,找出任意一点到另一点的路径,使得和最大.
从递归的来看...
如果只是一个节点,那么当然就是这个节点的值了.
如果这个作为root,那么最长路应该就是..
F(left) + F(right) + val...当然如果left,或者right<0就不用加了的= =
我盟从下往上找...
如果这个不是root,那么就不能把left和right加起来了...因为只是一条路...
/*** 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. */ public int ret = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { // write your code here if(null==root) return 0; rootPath(root); return ret; } public int rootPath(TreeNode root){ if(null==root) return 0; int sum = root.val; int left = rootPath(root.left); int right = rootPath(root.right); if(left>0){ sum += left; } if(right>0){ sum += right; } if(sum>ret){ ret = sum; } return Math.max(root.val, Math.max(left+root.val, right+root.val)); }}
0 0
- 题目:二叉树中的最大路径和
- LintCode-二叉树中的最大路径和
- 二叉树中的最大路径和
- 二叉树中的最大路径和
- 二叉树中的最大路径和
- 二叉树中的最大路径和
- lintcode,二叉树中的最大路径和
- 二叉树中的最大路径和
- 二叉树中的最大路径和
- 二叉树中的最大路径和-LintCode
- LintCode 二叉树中的最大路径和
- lintcode--二叉树中的最大路径和
- 二叉树中的最大路径和-LintCode
- 二叉树中的最大路径和
- 二叉树最大路径和
- 二叉树最大路径和
- 二叉树最大路径和
- lintcode-二叉树中的最大路径和-94
- 题目:二叉查找树中搜索区间
- HDU 1853--Cyclic Tour【最小费用最大流 && 有向环最小权值覆盖 】
- ZOJ 2104解题报告
- Java集合之Map
- django form关于clean及cleaned_data的说明 以及4种初始化
- 题目:二叉树中的最大路径和
- Android屏幕适配全攻略(最权威的官方适配指导)
- POJ 3185 The Water Bowls(高斯消元法,枚举自由变元)
- 开发中遇到detached head的解决方法
- install scrapy
- 关于继承的问题的一些讨论
- (5)Django框架学习-Forms篇
- python处理文本一处代码优化过程
- New THUer | 如何提高科研效率