leetcode[124]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 { public: int findMax(TreeNode *root,int &res) { if(root==NULL)return 0; int value=root->val; int left=findMax(root->left,res); int right=findMax(root->right,res); value+=left>0?left:0; value+=right>0?right:0; res=value>res?value:res; return max(root->val,max(root->val+left,root->val+right)); } int maxPathSum(TreeNode *root) { int res=INT_MIN; findMax(root,res); return res; } };