题解 | #二叉树中的最大路径和#
二叉树中的最大路径和
http://www.nowcoder.com/practice/da785ea0f64b442488c125b441a4ba4a
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型
*/
int dfs(TreeNode* root,int &ret){
if(!root) return 0;
int l = dfs(root->left,ret),r = dfs(root->right,ret);
int res = max(l + root->val,r + root->val);
ret = max(ret,max(max(res,root->val),l+r+root->val));
return max(res,root->val);
}
int maxPathSum(TreeNode* root) {
// write code here
int ret = INT_MIN;
dfs(root,ret);
return ret;
}
};