MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / maxPathSumHelper

Function maxPathSumHelper

cpp/Trees/maximum_path_sum.cpp:23–37  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

21}
22
23int maxPathSumHelper(TreeNode* node, int& maxSum) {
24 // Base case: null nodes have no path sum.
25 if (!node)
26 return 0;
27 // Collect the maximum gain we can attain from the left and right
28 // subtrees, setting them to 0 if they're negative.
29 int leftSum = std::max(maxPathSumHelper(node->left, maxSum), 0);
30 int rightSum = std::max(maxPathSumHelper(node->right, maxSum), 0);
31 // Update the overall maximum path sum if the current path sum is
32 // larger.
33 maxSum = std::max(maxSum, node->val + leftSum + rightSum);
34 // Return the maximum sum of a single, continuous path with the
35 // current node as an endpoint.
36 return node->val + std::max(leftSum, rightSum);
37}

Callers 1

maxPathSumFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected