lintcode--二叉树中的最大路径和
来源:互联网 发布:大数据怎样赚钱 编辑:程序博客网 时间:2024/05/22 08:13
给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)
给出一棵二叉树:
1 / \ 2 3
返回 6
/**
* 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 {
public int max ;
public int maxPathSum(TreeNode root) {
max = Integer.MIN_VALUE;
if(root == null) return 0;
maxpath(root);
return max;
}
public int maxpath(TreeNode root){
if(root == null) return 0;
int left = 0, right = 0;
if(root.left != null) left = Math.max(0, maxpath(root.left));
if(root.right != null) right = Math.max(0, maxpath(root.right));
max = Math.max(max, left + right + root.val);
return Math.max(left, right) + root.val;
}
}
- LintCode-二叉树中的最大路径和
- lintcode,二叉树中的最大路径和
- 二叉树中的最大路径和-LintCode
- LintCode 二叉树中的最大路径和
- lintcode--二叉树中的最大路径和
- 二叉树中的最大路径和-LintCode
- lintcode-二叉树中的最大路径和-94
- lintcode(94)二叉树中的最大路径和
- LintCode-分治-二叉树中的最大路径和
- [LintCode] Binary Tree Maximum Path Sum (二叉树中的最大路径和)
- lintcode binary-tree-maximum-path-sum 二叉树中的最大路径和
- 二叉树中的最大路径和
- 二叉树中的最大路径和
- 题目:二叉树中的最大路径和
- 二叉树中的最大路径和
- 二叉树中的最大路径和
- 二叉树中的最大路径和
- 二叉树中的最大路径和
- Centos yum软件管理
- 阿里巴巴js面试题1
- 【Java】NIO框架Netty——100万并发连接服务器资源消耗测试
- Comparable实现排序功能,重写排序方法
- 侧滑菜单(一)DrawerLayout的使用
- lintcode--二叉树中的最大路径和
- python3:迭代器
- 可编辑DIV设置光标位置
- extern与头文件(*.h)的区别和联系
- JavaMail实现发送邮件实测可用
- ionic APP上传到apple store
- 树状数组一(二)维区间修改与求和
- nginx 调测 优化
- artTemplate实现三层菜单