Skip to content

Commit e69d616

Browse files
authored
Create 1932-merge-bsts-to-create-single-bst.js
1 parent 2255c91 commit e69d616

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode[]} trees
11+
* @return {TreeNode}
12+
*/
13+
const canMerge = function (trees) {
14+
const mapRoots = {}
15+
const mapLeaves = {}
16+
let prev
17+
18+
//check all trees and hashMap all available roots and leaves
19+
for (let node of trees) {
20+
mapRoots[node.val] = node
21+
if (node.left != null) {
22+
if (mapLeaves[node.left.val] != null)
23+
//different nodes can't refer to the same node -> abnormal BST
24+
return null
25+
mapLeaves[node.left.val] = node.left
26+
}
27+
if (node.right != null) {
28+
if (mapLeaves[node.right.val] != null)
29+
//different nodes can't refer to the same node -> abnormal BST
30+
return null
31+
mapLeaves[node.right.val] = node.right
32+
}
33+
}
34+
35+
let rootRes = null
36+
let count = trees.length
37+
38+
//find potential root-result of the merged entire tree
39+
//that is node without any references from the parent leaf nodes
40+
for (let node of trees) {
41+
if (mapLeaves[node.val] == null) {
42+
rootRes = node
43+
break
44+
}
45+
}
46+
47+
//if there are no nodes like that -> abnormal BST
48+
if (rootRes == null) return rootRes
49+
50+
const q = []
51+
52+
//put root-result leaves into queue
53+
if (rootRes.left != null) q.push(rootRes.left)
54+
if (rootRes.right != null) q.push(rootRes.right)
55+
count--
56+
57+
while (q.length) {
58+
//get leaf from the queue and check if there is correponding available root
59+
let leaf = q.pop()
60+
let root = mapRoots[leaf.val]
61+
if (root != null) {
62+
//there is root matched to leaf, so let's merge it
63+
count--
64+
leaf.left = root.left
65+
leaf.right = root.right
66+
//add new leaves into the queue
67+
if (root.left != null) q.push(root.left)
68+
if (root.right != null) q.push(root.right)
69+
}
70+
}
71+
72+
prev = 0
73+
//if we have merged all inputed trees and that is valid BST by values, then return rootRes
74+
return count == 0 && recSanity(rootRes) ? rootRes : null
75+
76+
function recSanity(node) {
77+
if (node == null) return true
78+
79+
if (!recSanity(node.left)) return false
80+
81+
if (prev >= node.val) return false
82+
prev = node.val
83+
84+
return recSanity(node.right)
85+
}
86+
}

0 commit comments

Comments
 (0)