Merge BSTs to Create Single BST LeetCode solution in JavaScript

1
var canMerge = function (trees) {
2
let Node = {},
3
indeg = {};
4
// traverse the mini trees and put back pointers to their parents, also figure out the indegree of each node
5
let dfs = (node, leftparent = null, rightparent = null) => {
6
if (!node) return;
7
indeg[node.val] =
8
indeg[node.val] || Number(leftparent !== null || rightparent !== null);
9
(node.lp = leftparent), (node.rp = rightparent);
10
dfs(node.left, node, null), dfs(node.right, null, node);
11
};
12
for (let root of trees) (Node[root.val] = root), dfs(root);
13
//there are a lot of potential roots=> no bueno
14
if (
15
Object.values(indeg).reduce((a, b) => a + b) !=
16
Object.keys(indeg).length - 1
17
)
18
return null;
19
//find THE root
20
let bigRoot,
21
timesMerged = 0;
22
for (let root of trees) if (indeg[root.val] === 0) bigRoot = root;
23
// traverse the tree while replacing each leaf that can be replaced
24
let rec = (node = bigRoot) => {
25
if (!node) return;
26
if (!node.left && !node.right) {
27
let toadd = Node[node.val];
28
Node[node.val] = undefined; //invalidating the trees you already used
29
if (toadd === undefined) return;
30
//make the change
31
if (node.lp === null && node.rp === null) return;
32
else if (node.lp !== null) node.lp.left = toadd;
33
else node.rp.right = toadd;
34
timesMerged++;
35
rec(toadd);
36
} else rec(node.left), rec(node.right);
37
};
38
rec();
39
var isValidBST = function (node, l = -Infinity, r = Infinity) {
40
//l and r are the limits node.val should be within
41
if (!node) return true;
42
if (node.val < l || node.val > r) return false;
43
return (
44
isValidBST(node.left, l, node.val - 1) &&
45
isValidBST(node.right, node.val + 1, r)
46
);
47
};
48
//check if every item was used and if the result bst is valid
49
return !isValidBST(bigRoot) || timesMerged !== trees.length - 1
50
? null
51
: bigRoot;
52
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0