-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path124.cpp
39 lines (32 loc) · 924 Bytes
/
124.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 124. Binary Tree Maximum Path Sum - https://leetcode.com/problems/binary-tree-maximum-path-sum
#include "bits/stdc++.h"
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
private:
int answer = INT_MIN;
public:
int postorder(TreeNode* node) {
if (node == nullptr) { return 0; }
int L = postorder(node->left);
int R = postorder(node->right);
int max_side_sum = max(0, max(L, R)) + node->val;
int sum_highest_node = max(0, max(L, max(R, L + R))) + node->val;
answer = max(answer, sum_highest_node);
return max_side_sum;
}
int maxPathSum(TreeNode* root) {
postorder(root);
return answer;
}
};
int main() {
ios::sync_with_stdio(false);
return 0;
}