-
Notifications
You must be signed in to change notification settings - Fork 44
/
Problem93.js
82 lines (74 loc) · 2.01 KB
/
Problem93.js
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Problem 93
//
// This problem was asked by Apple.
//
// Given a tree, find the largest tree/subtree that is a BST.
//
// Given a tree, return the size of the largest tree/subtree that is a BST.
//
// O(N) Time complexity
// O(d) Space complexity
// N is the number of nodes in the tree. d is the depth of the tree
/**
* Returns the largest tree/subtree that is a BST.
* @param {TreeNode} root
* @return {TreeNode}
*/
function largestBST(root) {
const largest = largestBSTHelper(root);
return largest.data;
}
/**
* Returns the size of the largest tree/subtree that is a BST.
* @param {TreeNode} root
* @return {number}
*/
function sizeOfLargestBST(root) {
const largest = largestBSTHelper(root);
return largest.size;
}
class BSTInfo {
constructor(
min = Number.MAX_SAFE_INTEGER,
max = Number.MIN_SAFE_INTEGER,
isBST = true,
size = 0,
data = null
) {
this.min = min;
this.max = max;
this.isBST = isBST;
this.size = size;
this.data = data;
}
}
/**
* Returns the information of the largest tree/subtree that is a BST
* @param {TreeNode} root
* @return {BSTInfo}
*/
function largestBSTHelper(root) {
if (root === null) return new BSTInfo();
const leftBSTInfo = largestBSTHelper(root.left);
const rightBSTInfo = largestBSTHelper(root.right);
if (
!leftBSTInfo.isBST ||
!rightBSTInfo.isBST ||
leftBSTInfo.max > root.val ||
rightBSTInfo.min <= root.val
) {
const size = Math.max(leftBSTInfo.size, rightBSTInfo.size);
// store largest bst so far
const BST =
leftBSTInfo.size > rightBSTInfo.size
? leftBSTInfo.data
: rightBSTInfo.data;
// min and max does not matter because of isBST false property
return new BSTInfo(-1, -1, false, size, BST);
}
const size = leftBSTInfo.size + rightBSTInfo.size + 1;
const min = root.left !== null ? leftBSTInfo.min : root.val;
const max = root.right !== null ? rightBSTInfo.max : root.val;
return new BSTInfo(min, max, true, size, root);
}
export { largestBST, sizeOfLargestBST };