【LeetCode】#124二叉树中的最大路径和(Binary Tree Maximum Path Sum)
题目描述
给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
示例
示例 1:
输入: [1,2,3]
1
/
2 3
输出: 6
示例 2:
输入: [-10,9,20,null,null,15,7]
-10
/
9 20
/
15 7
输出: 42
Description
Given a non-empty 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.
Example
Example 1:
Input: [1,2,3]
1
/
2 3
Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7]
-10
/
9 20
/
15 7
Output: 42
解法
class Solution {
int res;
public int maxPathSum(TreeNode root) {
res = root.val;
helper(root);
return res;
}
public int helper(TreeNode node){
int sum;
if(node.left==null && node.right==null){
sum = node.val;
}else if(node.left==null){
int right = helper(node.right);
sum = right>0 ? right+node.val : node.val;
}else if(node.right==null){
int left = helper(node.left);
sum = left>0 ? left+node.val : node.val;
}else{
int left = helper(node.left);
int right = helper(node.right);
res = Math.max(res, left+right+node.val);
int max = Math.max(left, right);
sum = max>0 ? max+node.val : node.val;
}
res = Math.max(res, sum);
return sum;
}
}