题目:
代码(首刷看解析 2024年3月6日):
/**
* 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 recursion(TreeNode* root, int& maxlen) {
if (!root) return 0;
int left = recursion(root->left, maxlen);
int right = recursion(root->right, maxlen);
// todo:
maxlen = max(maxlen, max(left, 0) + max(right, 0) + root->val);
return root->val + max(0, max(left, right));
}
int maxPathSum(TreeNode* root) {
if (!root) return 0;
int maxlen = INT_MIN;
recursion(root, maxlen);
return maxlen;
}
};
代码(二刷自解 2024年8月9日)
进化了,感觉这题不难呀?为什么是hard
class Solution {
private:
int maxResult;
int backRecursive(TreeNode* root) {
if (!root) return 0;
int l = backRecursive(root->left);
int r = backRecursive(root->right);
// 根据左右节点返回的数字,计算带上自身的最大序列和
if (l < 0) l = 0;
if (r < 0) r = 0;
int temp = root->val + l + r;
maxResult = max(temp, maxResult);
return max(root->val + r, root->val + l);
}
public:
int maxPathSum(TreeNode* root) {
// 后序遍历,记录每个节点以自身为最高的节点的最长序列和
maxResult = INT_MIN;
backRecursive(root);
return maxResult;
}
};