# 【LeetCode】 124. Binary Tree Maximum Path Sum
## 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
```
## Solution
* 這題其實感覺蠻簡單的,我自己撰寫的時候卻一直莫名碰壁,後來還是參考了他人的code才過QQ
* 我們先做一個function是找到經過節點`n`並將`n`當作樹根的最大路徑和。接著跑每一個點找出最大值即可。
* 對於自己這個節點來說,最大值就是(自己 + 左邊最大 + 右邊最大)。
* 其中左邊和右邊如果為負值可以不加,所以用一個`max(0, XXX)`來處理。
* 但是在找最大路徑時,左邊和右邊只能選一邊走,因此要回傳(自己 + `max(左邊最大, 又邊最大)`)。
### Code
```C++=1
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int find(TreeNode* node, int& ans)
{
if(!node) return 0;
int right = max(find(node->right, ans), 0);
int left = max(find(node->left, ans), 0);
ans = max(ans, node->val + right + left);
return node->val + max(right, left);
}
int maxPathSum(TreeNode* root) {
int ans = -10000;
find(root, ans);
return ans;
}
};
```
###### tags: `LeetCode` `C++`