您的位置:首页 > 其它

leetcode--Binary Tree Maximum Path Sum

2015-07-11 00:16 387 查看
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,

1
/ \
2   3


Return
6
.

题意:对于给定二叉树,查找最长路径和。该路径的起点,终点可以是二叉树的任意一个节点。

分类:二叉树

解法1:以采用Binary Tree最常用的dfs来进行遍历。先算出左右子树的结果L和R,如果L大于0,那么对后续结果是有利的,我们加上L,如果R大于0,对后续结果也是有利的,继续加上R。

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxPathSum(TreeNode root) {
max = Integer.MIN_VALUE;
dfs(root);
return max;
}

int max = 0;//最大值
/**
* 该方法返回包含t节点的最大路径和
*/
int dfs(TreeNode t){
if(t==null) return 0;//如果为空,路径和为0
int left = dfs(t.left);//包含左节点的最大路径和left
int right = dfs(t.right);//包含右节点的最大路径和right
int curmax = t.val;//当前节点,当前和
if(left>0) curmax += left;//如果左节点不为0,加上
if(right>0) curmax += right;//如果右节点不为0,也加上
max = Math.max(max,curmax);//与当前最大值比较,更新
if(left>0||right>0){//如果左节点或者右节点,大于0
return left>right?left+t.val:right+t.val;
}else{//如果左右节点都是负数或者0,返回当前节点值即可
return t.val;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: