Create Binary Tree From Descriptions LeetCode solution in JavaScript

1
var createBinaryTree = function (descriptions) {
2
let nodes = new Map(),
3
children = new Set();
4
for (let [parent, child, isLeft] of descriptions) {
5
let parentNode = nodes.get(parent) || new TreeNode(parent);
6
if (!nodes.has(parent)) nodes.set(parent, parentNode);
7

8
let childNode = nodes.get(child) || new TreeNode(child);
9
if (!nodes.has(child)) nodes.set(child, childNode);
10

11
if (isLeft) parentNode.left = childNode;
12
else parentNode.right = childNode;
13

14
children.add(child);
15
}
16

17
for (let [parent, child, isLeft] of descriptions) {
18
// a node with no parent is the root
19
if (!children.has(parent)) return nodes.get(parent);
20
}
21
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0