-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2196-create-binary-tree-from-descriptions.js
More file actions
54 lines (50 loc) · 1.51 KB
/
2196-create-binary-tree-from-descriptions.js
File metadata and controls
54 lines (50 loc) · 1.51 KB
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
/**
* 2196. Create Binary Tree From Descriptions
* https://leetcode.com/problems/create-binary-tree-from-descriptions/
* Difficulty: Medium
*
* You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti]
* indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore,
* - If isLefti == 1, then childi is the left child of parenti.
* - If isLefti == 0, then childi is the right child of parenti.
*
* Construct the binary tree described by descriptions and return its root.
*
* The test cases will be generated such that the binary tree is valid.
*/
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {number[][]} descriptions
* @return {TreeNode}
*/
var createBinaryTree = function(descriptions) {
const nodes = new Map();
const children = new Set();
for (const [parent, child, isLeft] of descriptions) {
if (!nodes.has(parent)) {
nodes.set(parent, new TreeNode(parent));
}
if (!nodes.has(child)) {
nodes.set(child, new TreeNode(child));
}
children.add(child);
if (isLeft) {
nodes.get(parent).left = nodes.get(child);
} else {
nodes.get(parent).right = nodes.get(child);
}
}
for (const [val, node] of nodes) {
if (!children.has(val)) {
return node;
}
}
return null;
};