Binary Tree Maximum Path Sum LeetCode solution in C++
1class Solution {2public:3int rec(TreeNode *root, int &res) {4if (root == nullptr) return 0;5// maximum value from left6int l = rec(root->left, res);7// maximum value from right8int r = rec(root->right, res);910// check if path can go through this node ,if yes upadte the result value11res = max(res, root->val + l + r);1213// return the maximum non-negative path value14return max({l + root->val, r + root->val, 0});15}16int maxPathSum(TreeNode *root) {17int res = INT_MIN;18int x = rec(root, res);19return res;20}21};