[LeetCode]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
.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: int ans; public: int DFS(TreeNode *root) { if(root==NULL) return 0; else { int sum=root->val; int sum1=DFS(root->left); int sum2=DFS(root->right); if(sum1>0) sum+=sum1; if(sum2>0) sum+=sum2; ans=max(ans,sum); return max(root->val,max(root->val+sum1,root->val+sum2)); } } int maxPathSum(TreeNode *root) { if(root==NULL) return 0; ans=root->val; return max(ans,DFS(root)); } };