Binary Tree Maximum Path Sum LeetCode solution in C++

1
class Solution {
2
public:
3
int rec(TreeNode *root, int &res) {
4
if (root == nullptr) return 0;
5
// maximum value from left
6
int l = rec(root->left, res);
7
// maximum value from right
8
int r = rec(root->right, res);
9

10
// check if path can go through this node ,if yes upadte the result value
11
res = max(res, root->val + l + r);
12

13
// return the maximum non-negative path value
14
return max({l + root->val, r + root->val, 0});
15
}
16
int maxPathSum(TreeNode *root) {
17
int res = INT_MIN;
18
int x = rec(root, res);
19
return res;
20
}
21
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0