# Hard-题目32：124. Binary Tree Maximum Path Sum

80人阅读 评论(0)

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 does not need to go through the root.

For example:
Given the below binary tree,

   1
/ \
2   3


Return 6.

public class Solution {
public int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
rec(root);
return max;
}

public int rec(TreeNode root){
if(root == null){
return 0;
}

int leftSubtreeMaxSum = rec(root.left);     // 左子树的最大和
int rightSubtreeMaxSum = rec(root.right);       // 右子树的最大和
int arch = leftSubtreeMaxSum + root.val + rightSubtreeMaxSum;
int maxPathAcrossRootToParent = Math.max(root.val, Math.max(leftSubtreeMaxSum, rightSubtreeMaxSum)+root.val);
max = Math.max(max, Math.max(arch, maxPathAcrossRootToParent));

return maxPathAcrossRootToParent;
}
}

2ms,23.37%,2ms,76.33%
cmershen的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：56151次
• 积分：3202
• 等级：
• 排名：第10668名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论