Tree9

题目描述[原题链接][https://leetcode-cn.com/problems/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

算法描述

​ 每次找左右子树最大权值的路径进行延申,找到最大路径和;

C++代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int val = INT_MIN;
int caculate(TreeNode* root){
if(root==NULL)return 0;
int left = max(0,caculate(root->left));
int right = max(0,caculate(root->right));
int p = root->val+left+right;
val = max(val,p);
return root->val+max(left,right);
}
int maxPathSum(TreeNode* root) {
caculate(root);
return val;
}
};

Java代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int val = Integer.MIN_VALUE;
public int maxPathSum2(TreeNode root){
if(root==null)return 0;
int left = Math.max(0,maxPathSum2(root.left));
int right = Math.max(0,maxPathSum2(root.right));
int p = root.val+left+right;
val = Math.max(val,p);
return root.val+Math.max(left,right);
}

public int maxPathSum(TreeNode root) {
maxPathSum2(root);
return val;
}
}