原题链接:124. 二叉树中的最大路径和
solution:
递归求解问题:
① 最大路径可能是以当前节点值和左右子树的路径和
② 函数返回值为以root为根节点的最大路径
③ 递归更新最大路径
class Solution {
public:
int res = INT_MIN; //定义返回值
int maxPathSum(TreeNode* root) {
countPath(root);
return res;
}
int countPath(TreeNode *root) {
if(root == nullptr) return 0;
int l = countPath(root->left),r = countPath(root->right);
int left = l < 0 ? 0 : l; //返回以左儿子为根节点的最大路径和
int right = r < 0 ? 0 : r; //返回以右儿子为根节点的最大路径和
int value = left + right + root->val;
res = max(res, value); //判断最大值是不是以当前根节点和左右路径的和
return max(left,right) + root->val; //最大路径只能是左或右大的那一条边
}
};