解法1
- 解法
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public:int maxPathSum(TreeNode* root) {if(!root) return 0;int result = numeric_limits<int>::min();dfs(result, root);return result;}int dfs(int &result, TreeNode *root){if(!root) return 0;int left = dfs(result, root->left);int right = dfs(result, root->right);result = max(result, root->val + left + right);int temp = max(left + root->val, right + root->val);return max(0, temp);}
};