【二叉树(DFS)- LeetCode】124. 二叉树中的最大路径和
题目:
124. 二叉树中的最大路径和
题解
DFS
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
private:int maxSum = INT_MIN;
public:int maxGain(TreeNode* node){if(node == nullptr){return 0;}// 子树递归计算贡献值,如果是负数的则不选择,也就是0int l = max(maxGain(node->left), 0);int r = max(maxGain(node->right), 0);int tmp_sum = l + r + node->val;maxSum = max(tmp_sum, maxSum);return node->val+max(l,r);}int maxPathSum(TreeNode* root) {maxGain(root);return maxSum;}
};