您的位置:首页 > 其它

二叉树的最长路径和(Binary Tree Maximum Path Sum)

2017-10-10 17:00 405 查看

题目:

Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root

google 翻译:

给定一个二叉树,找到最大路径和。 对于这个问题,路径被定义为从父子连接到某个起始节点到树中任何节点的任何节点序列。 该路径必须包含至少一个节点,不需要遍历根。

示例:



就是从任意节点开始到任意节点结束所走过的最大距离

思路:

最大值的可能情况,虽然题目说不需要遍历根节点,其实是需要根节点的。

把根节点理解成父节点更好一些,因为需要父节点和别的连成一条线。

最大值来自

root+左边的某条路径+右边的某条路径

左边的某条路径 + root

root + 右边的某条路径

root

练习传送门:这里

java实现:

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
record(root);
return max;
}
public int record(TreeNode root){
if(root==null) return 0;
int l=Math.max(0,record(root.left));
int r=Math.max(0,record(root.right));
max=Math.max(max,root.val+l+r);
return root.val+Math.max(l,r);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: