# 二叉树中的最大路径和
路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。
路径和 是路径中各节点值的总和。
给你一个二叉树的根节点 root
,返回其 最大路径和 。
示例 1:
输入:root = [1,2,3]
输出:6
解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6
示例 2:
输入:root = [-10,9,20,null,null,15,7]
输出:42
解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
提示:
- 树中节点数目范围是
[1, 3 * 104]
-1000 <= Node.val <= 1000
以下错误的选项是?
## aop
### before
```cpp
#include
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
```
### after
```cpp
```
## 答案
```cpp
class Solution
{
public:
int maxv = -123123632;
int maxPathSum(TreeNode *root)
{
if (root == NULL)
return 0;
calc(root);
return maxv;
}
int calc(TreeNode *root)
{
if (root == NULL)
return 0;
int temp = root->val;
int lmaxsum = calc(root->left);
int rmaxsum = calc(root->right);
if (lmaxsum > 0)
temp += lmaxsum;
if (rmaxsum > 0)
temp += rmaxsum;
return max(root->val, max(root->val + lmaxsum, root->val + rmaxsum));
}
};
```
## 选项
### A
```cpp
class Solution
{
int res = INT_MIN;
public:
int maxPathSum(TreeNode *root)
{
int p = getdfs(root);
return res;
}
int getdfs(TreeNode *node)
{
if (node == NULL)
return 0;
int left = max(getdfs(node->left), 0);
int right = max(getdfs(node->right), 0);
int size = left + right + node->val;
res = res > size ? res : size;
right = right > left ? right : left;
node->val = right + node->val;
return node->val;
}
};
```
### B
```cpp
class Solution
{
public:
int ans = 0;
int OneSideMax(TreeNode *root)
{
if (root == nullptr)
return 0;
int left = max(0, OneSideMax(root->left));
int right = max(0, OneSideMax(root->right));
ans = max(ans, left + right + root->val);
return max(left, right) + root->val;
}
int maxPathSum(TreeNode *root)
{
OneSideMax(root);
return ans;
}
};
```
### C
```cpp
class Solution
{
public:
int dfs(TreeNode *root, int &res)
{
if (root == NULL)
{
return 0;
}
int left = max(dfs(root->left, res), 0);
int right = max(dfs(root->right, res), 0);
res = max(res, root->val + left + right);
return root->val + max(left, right);
}
int maxPathSum(TreeNode *root)
{
int res = INT_MIN;
dfs(root, res);
return res;
}
};
```