# 二叉树中的最大路径和

<p><strong>路径</strong> 被定义为一条从树中任意节点出发，沿父节点-子节点连接，达到任意节点的序列。同一个节点在一条路径序列中 <strong>至多出现一次</strong> 。该路径<strong> 至少包含一个 </strong>节点，且不一定经过根节点。</p>

<p><strong>路径和</strong> 是路径中各节点值的总和。</p>

<p>给你一个二叉树的根节点 <code>root</code> ，返回其 <strong>最大路径和</strong> 。</p>

<p> </p>

<p><strong>示例 1：</strong></p>
<img alt="" src="https://img-service.csdnimg.cn/img_convert/ca0d0d9f728f2aeda1976de9b08940e5.jpeg" style="width: 322px; height: 182px;" />
<pre>
<strong>输入：</strong>root = [1,2,3]
<strong>输出：</strong>6
<strong>解释：</strong>最优路径是 2 -> 1 -> 3 ，路径和为 2 + 1 + 3 = 6</pre>

<p><strong>示例 2：</strong></p>
<img alt="" src="https://img-service.csdnimg.cn/img_convert/730fd58fb57c0fbc6d5f77b18e9d6b50.jpeg" />
<pre>
<strong>输入：</strong>root = [-10,9,20,null,null,15,7]
<strong>输出：</strong>42
<strong>解释：</strong>最优路径是 15 -> 20 -> 7 ，路径和为 15 + 20 + 7 = 42
</pre>

<p> </p>

<p><strong>提示：</strong></p>

<ul>
	<li>树中节点数目范围是 <code>[1, 3 * 10<sup>4</sup>]</code></li>
	<li><code>-1000 <= Node.val <= 1000</code></li>
</ul>


## template

```cpp
#include <bits/stdc++.h>
using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution
{
public:
    int maxPathSum(TreeNode *root)
    {
        if (!root)
            return 0;
        vector<TreeNode *> ss;
        unordered_map<TreeNode *, int> val;
        ss.push_back(root);
        int len = 1;
        queue<TreeNode *> q{{root}};
        while (!q.empty())
        {
            TreeNode *t = q.front();
            q.pop();
            cout << t->val << endl;
            if (t->left)
            {
                len++;
                q.push(t->left);
                ss.push_back(t->left);
            }
            if (t->right)
            {
                len++;
                q.push(t->right);
                ss.push_back(t->right);
            }
        }

        int res = INT_MIN;

        while (len > 0)
        {
            TreeNode *node = ss[--len];
            int ps = node->val;
            int s = ps;

            int ls = max(0, val[node->left]);
            int rs = max(0, val[node->right]);

            ps += max(ls, rs);
            val[node] = ps;

            s += ls + rs;
            res = max(s, res);
        }

        return res;
    }
};


```

## 答案

```cpp

```

## 选项

### A

```cpp

```

### B

```cpp

```

### C

```cpp

```