leetcode-124-Binary Tree Maximum Path Sum

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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

对于每条路径,都有一个最高节点,每个节点都可以看作一个最高节点,所有最高节点中的最大值即为所求。因此可以递归求解,对于每个最高节点,路径肯定包含其节点的值,左或右子树的最大路径不能为负,否则取0,分别左右子树的最大路径和最高节点的值累加,即为以最高节点为根的最大路径和,更新maxSum;另外对于每个最高节点,只能返回路径值较大一侧的子树给上一层,否则不符题意。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* 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) {
maxPathDown(root);
return ans;
}
int maxPathDown(TreeNode* root){
if(root==NULL) return 0;
int left=max(0,maxPathDown(root->left));
int right=max(0,maxPathDown(root->right));
ans=max(ans,root->val+left+right);
return root->val+max(0,max(left,right));
}
private:
int ans=INT_MIN;

};
Donate? comment?