Skip to content

Commit fe9820f

Browse files
committed
Add solution #333
1 parent 0df80fb commit fe9820f

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,7 @@
321321
330|[Patching Array](./solutions/0330-patching-array.js)|Hard|
322322
331|[Verify Preorder Serialization of a Binary Tree](./solutions/0331-verify-preorder-serialization-of-a-binary-tree.js)|Medium|
323323
332|[Reconstruct Itinerary](./solutions/0332-reconstruct-itinerary.js)|Hard|
324+
333|[Largest BST Subtree](./solutions/0333-largest-bst-subtree.js)|Medium|
324325
334|[Increasing Triplet Subsequence](./solutions/0334-increasing-triplet-subsequence.js)|Medium|
325326
335|[Self Crossing](./solutions/0335-self-crossing.js)|Hard|
326327
336|[Palindrome Pairs](./solutions/0336-palindrome-pairs.js)|Hard|

solutions/0333-largest-bst-subtree.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* 333. Largest BST Subtree
3+
* https://leetcode.com/problems/largest-bst-subtree/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary tree, find the largest subtree, which is also a Binary Search
7+
* Tree (BST), where the largest means subtree has the largest number of nodes.
8+
*
9+
* A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned
10+
* properties:
11+
* - The left subtree values are less than the value of their parent (root) node's value.
12+
* - The right subtree values are greater than the value of their parent (root) node's value.
13+
*
14+
* Note: A subtree must include all of its descendants.
15+
*/
16+
17+
/**
18+
* Definition for a binary tree node.
19+
* function TreeNode(val, left, right) {
20+
* this.val = (val===undefined ? 0 : val)
21+
* this.left = (left===undefined ? null : left)
22+
* this.right = (right===undefined ? null : right)
23+
* }
24+
*/
25+
/**
26+
* @param {TreeNode} root
27+
* @return {number}
28+
*/
29+
var largestBSTSubtree = function(root) {
30+
let maxSize = 0;
31+
traverse(root);
32+
return maxSize;
33+
34+
function traverse(node) {
35+
if (!node) return { isBST: true, size: 0, min: Infinity, max: -Infinity };
36+
37+
const left = traverse(node.left);
38+
const right = traverse(node.right);
39+
if (left.isBST && right.isBST && node.val > left.max && node.val < right.min) {
40+
const size = left.size + right.size + 1;
41+
maxSize = Math.max(maxSize, size);
42+
return {
43+
isBST: true,
44+
size,
45+
min: Math.min(left.min, node.val),
46+
max: Math.max(right.max, node.val)
47+
};
48+
}
49+
50+
return { isBST: false, size: 0, min: 0, max: 0 };
51+
}
52+
};

0 commit comments

Comments
 (0)