标签:node loading inf img 路径 pat color alt lazy
1 class Solution { 2 private: 3 int maxSum = INT_MIN; 4 5 public: 6 int maxGain(TreeNode* node) { 7 if (node == nullptr) { 8 return 0; 9 } 10 11 // 递归计算左右子节点的最大贡献值 12 // 只有在最大贡献值大于 0 时,才会选取对应子节点 13 int leftGain = max(maxGain(node->left), 0); 14 int rightGain = max(maxGain(node->right), 0); 15 16 // 节点的最大路径和取决于该节点的值与该节点的左右子节点的最大贡献值 17 int priceNewpath = node->val + leftGain + rightGain; 18 19 // 更新答案 20 maxSum = max(maxSum, priceNewpath); 21 22 // 返回节点的最大贡献值 23 return node->val + max(leftGain, rightGain); 24 } 25 26 int maxPathSum(TreeNode* root) { 27 maxGain(root); 28 return maxSum; 29 } 30 };
标签:node loading inf img 路径 pat color alt lazy
原文地址:https://www.cnblogs.com/libin123/p/14604473.html