【力扣hot100题】(049)二叉树中的最大路径和
递归,新建递归函数返回是根节点的最大向下路径值,每次递归可以通过左右的递归值判断当前节点要不要连接左右节点,由此更新result,并且返回当前节点连接左右节点中最大的那个节点(或是选择不连接)的值。
/**
* 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 result=-1001;
int maxPath(TreeNode* root){
if(root==nullptr) return 0;
int l=maxPath(root->left);
int r=maxPath(root->right);
if(l>=0&&r>=0) result=max(result,l+r+root->val);
else if(l>=0) result=max(result,root->val+l);
else if(r>=0) result=max(result,root->val+r);
else{
result=max(result,root->val);
return root->val;
}
return root->val+max(l,r);
}
int maxPathSum(TreeNode* root){
result=max(result,maxPath(root));
return result;
}
};