[LeetCode] Maximum Sum BST in Binary Tree

1373. Maximum Sum BST in Binary Tree

Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node’s key.
  • The right subtree of a node contains only nodes with keys greater than the node’s key.
  • Both the left and right subtrees must also be binary search trees.
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
40
41
42
43
44
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
long long res = 0;
array<long long, 3> helper(TreeNode* node) {
if(!node->left and !node->right) {
res = max(res, (long long) node->val);
return {node->val, node->val, node->val};
}
long long mi = node->val, ma = node->val, sum = node->val;
bool valid = true;
if(node->left) {
auto [lmi, lma, lsum] = helper(node->left);
if(lma >= node->val) valid = false;
mi = lmi;
sum += lsum;
}
if(node->right) {
auto [rmi, rma, rsum] = helper(node->right);
if(rmi <= node->val) valid = false;
ma = rma;
sum += rsum;
}
if(valid) {
res = max(res, sum);
return {mi, ma, sum};
}
return {INT_MIN, INT_MAX, INT_MIN};
}
public:
int maxSumBST(TreeNode* root) {
helper(root);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/01/PS/LeetCode/maximum-sum-bst-in-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.