1
var canMerge = function (trees) {4
// traverse the mini trees and put back pointers to their parents, also figure out the indegree of each node5
let dfs = (node, leftparent = null, rightparent = null) => {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);12
for (let root of trees) (Node[root.val] = root), dfs(root);13
//there are a lot of potential roots=> no bueno15
Object.values(indeg).reduce((a, b) => a + b) !=16
Object.keys(indeg).length - 122
for (let root of trees) if (indeg[root.val] === 0) bigRoot = root;23
// traverse the tree while replacing each leaf that can be replaced24
let rec = (node = bigRoot) => {26
if (!node.left && !node.right) {27
let toadd = Node[node.val];28
Node[node.val] = undefined; //invalidating the trees you already used29
if (toadd === undefined) return;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;36
} else rec(node.left), rec(node.right);39
var isValidBST = function (node, l = -Infinity, r = Infinity) {40
//l and r are the limits node.val should be within41
if (!node) return true;42
if (node.val < l || node.val > r) return false;44
isValidBST(node.left, l, node.val - 1) &&45
isValidBST(node.right, node.val + 1, r)48
//check if every item was used and if the result bst is valid49
return !isValidBST(bigRoot) || timesMerged !== trees.length - 1