[LeetCode] Largest BST Subtree

333. Largest BST Subtree

Given the root of a binary tree, find the largest subtree, which is also a Binary Search Tree (BST), where the largest means subtree has the largest number of nodes.

A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties:

  • The left subtree values are less than the value of their parent (root) node’s value.
  • The right subtree values are greater than the value of their parent (root) node’s value.

Note: A subtree must include all of its descendants.

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
/**
* 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 {
int res = 0;
pair<bool, int> helper(TreeNode* node, int mi, int ma) {
if(!node) return {true, 0};
if(mi < node->val and node->val < ma) {
auto [lbst, lsub] = helper(node->left, mi, node->val);
auto [rbst, rsub] = helper(node->right, node->val, ma);

if(lbst and rbst) {
res = max(res, lsub + rsub + 1);
return {true, lsub + rsub + 1};
}
}
auto [lbst, lsub] = helper(node->left, INT_MIN, node->val);
auto [rbst, rsub] = helper(node->right, node->val, INT_MAX);
if(lbst and rbst) {
res = max(res,lsub + rsub + 1);
}
return {false, 0};
}
public:
int largestBSTSubtree(TreeNode* root) {
helper(root, INT_MIN, INT_MAX);
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/13/PS/LeetCode/largest-bst-subtree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.