昨天晚上写了大概 今天晚上调了不到20分钟 做出了hard
撒花
就是dfs+dp的结合
之前在微软面经看到过:)
124. Binary Tree Maximum Path Sum
Hard
1992150FavoriteShare
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
/**
* 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 maxn;
int maxSum(TreeNode* root) {
if (root==NULL) {
return 0;
}
maxn = max(maxn,root->val);
if (root->left==NULL&&root->right==NULL) {
return root->val;
}
int left = 0, right = 0;
if (root->left) {
left = maxSum(root->left);
maxn = max(left+root->val,maxn);
}
if (root->right) {
right = maxSum(root->right);
maxn = max(right+root->val, maxn);
}
maxn = max(maxn, left+root->val+right);
return root->val+max(0,max(right,left));
}
int maxPathSum(TreeNode* root) {
maxn = root->val;
maxSum(root);
return maxn;
}
};