【DFS&二叉树】Binary Tree Maximum Path Sum
2014-04-03 21:09
253 查看
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
注意特殊情况:左右路径为负的情况,只能选择根节点的值
public class Solution {
private int max;
public int dfs(TreeNode p){
if(p == null) return 0;
int left = dfs(p.left);
int right = dfs(p.right);
int sum = p.val;
if(left > 0)
sum += left;
if(right > 0)
sum += right;
max = Math.max(sum , max);
return p.val + (Math.max(left, right)>0 ? Math.max(left, right) : 0);
}
public int maxPathSum(TreeNode root) {
max = Integer.MIN_VALUE;
dfs(root);
return max;
}
}
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / \ 2 3
注意特殊情况:左右路径为负的情况,只能选择根节点的值
public class Solution {
private int max;
public int dfs(TreeNode p){
if(p == null) return 0;
int left = dfs(p.left);
int right = dfs(p.right);
int sum = p.val;
if(left > 0)
sum += left;
if(right > 0)
sum += right;
max = Math.max(sum , max);
return p.val + (Math.max(left, right)>0 ? Math.max(left, right) : 0);
}
public int maxPathSum(TreeNode root) {
max = Integer.MIN_VALUE;
dfs(root);
return max;
}
}
相关文章推荐
- 2014开源技术大会(读书汇)
- 冒烟测试、α测试、Beta测试、性能测试
- 冒烟测试、α测试、Beta测试、性能测试
- 日积月累:ListView的属性详解和探究
- ( ubuntu )linux快捷键
- jvm的参数含义及设置
- NSOpenPanel 设置允许打开的文件类型
- android的事件处理1(监听 回调 handle)
- Object Oriented Design -- Data and Algorithm Separation (1)
- jekyll安装
- 2014开源技术大会(读书汇)
- 2014开源技术大会(读书汇)
- SharePoint 2013开发入门探索(一)- 自定义列表
- fcntl函数说明
- javascript弹出框打印某个数值时,弹出NaN?(not a number)
- 微信公众开放平台开发05---jetty部署异常:rg.apache.jasper.JasperException: PWC6345: There is an error in invoking ja
- java内存管理之二
- java内存管理之一
- 第四周作业---图的表示
- hdu 1164