124. 二叉树中的最大路径和
作者:互联网
本质上是一个分治法。要记录每个节点的最大路径,同时记录maxPath. maxPath 可能包含左右路径。
class Solution {
private:
int maxPath = INT_MIN;
public:
int singlePathMax(TreeNode* root){
if(root == NULL) return 0;
int left_gain = max(singlePathMax(root->left), 0);
int right_gain = max(singlePathMax(root->right), 0);
maxPath = max(maxPath, root->val+left_gain+right_gain);
return root->val + max(left_gain, right_gain);
}
int maxPathSum(TreeNode* root) {
singlePathMax(root);
return maxPath;
}
};
标签:right,int,路径,singlePathMax,maxPath,124,二叉树,root,gain 来源: https://blog.csdn.net/declanzane/article/details/104733726