[InterviewBit] Max Sum Path in Binary Tree

Max Sum Path in Binary Tree

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int res;
int dfs(TreeNode* A) {
if(A == NULL) return 0;
int l = dfs(A->left), r = dfs(A->right);
res = max(res, l + r + A->val);
res = max(res, max({l,r,0}) + A->val);
return max({l,r,0}) + A->val;
}
int Solution::maxPathSum(TreeNode* A) {
res = INT_MIN;
dfs(A);
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/10/PS/interviewbit/max-sum-path-in-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.