# 124. Binary Tree Maximum Path Sum 二叉树中的最大路径和

@TOC

## # 题目描述

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 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
``````

## # 解题方法

### # 递归

``````经过一个节点的最大路径 = max(其左孩子为顶点的最大路径, 0) + max(右孩子为顶点的最大路径, 0) + 该节点的值。
``````

``````   2
/ \
9  20
/  \
15   7

``````

C++代码如下：

``````/**
* 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 maxPathSum(TreeNode* root) {
if (!root) return 0;
maxPathToLeaf(root);
return res;
}
int maxPathToLeaf(TreeNode* root) {
if (!root) return 0;
int left = maxPathToLeaf(root->left);
int right = maxPathToLeaf(root->right);
if (left < 0)
left = 0;
if (right < 0)
right = 0;
res = max(res, left + right + root->val);
return root->val + max(left, right);
}
private:
int res = INT_MIN;
};
``````

543. Diameter of Binary Treeopen in new window

## # 日期

2019 年 9 月 27 日 —— 昨天面快手，竟然是纯刷题