Problem
Hint
DFS
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxPath(struct TreeNode *root,int *rec){
if(root==NULL) return 0;
int left = maxPath(root->left,rec);
int right = maxPath(root->right,rec);
if(left<0) left = 0;
if(right<0) right = 0;
*rec = *rec>left+right+root->val?*rec:left+right+root->val;
return (left>right?left:right)+root->val;
}
int maxPathSum(struct TreeNode* root) {
int max = 0x80000000;
maxPath(root,&max);
return max;
}
The elegance of algorithm must be tasted by racking your brain. : )