【leetcode】Binary Tree Maximum Path Sum

时间:2023-03-09 00:45:29
【leetcode】Binary Tree Maximum Path Sum

Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1
/ \
2 3

Return 6.

用递归确定每一个节点作为root时,从root出发的最长的路径
在每一次递归中计算maxPath
 /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxSum=INT_MIN;
int maxPathSum(TreeNode *root) { DFS(root);
return maxSum;
} int DFS(TreeNode *root)
{
if(root==NULL)
{
return ;
} int left=DFS(root->left);
int right=DFS(root->right); int sum=root->val;
if(left>) sum+=left;
if(right>) sum+=right;
if(maxSum<sum) maxSum=sum; return (left>||right>)?root->val+max(left,right):root->val;
}
};