[Geeks for Geeks] Maximum path sum from any node

Maximum path sum from any node

Given a binary tree, the task is to find the maximum path sum. The path may start and end at any node in the tree.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

class Solution {
int res = INT_MIN;
int helper(Node* node) {
if(!node) return 0;
int l = helper(node->left);
int r = helper(node->right);
res = max(res, l + r + node->data);
int ma = max(max(l,r) + node->data, node->data);
res = max(res, ma);
return ma;
}
public:
//Function to return maximum path sum from any node in a tree.
int findMaxSum(Node* root)
{
helper(root);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/maximum-path-sum-from-any-node/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.