-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utils.js
115 lines (94 loc) · 2.4 KB
/
Utils.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
export function toOrderedBinaryTree(nodesList) {
var f = function insertBinTree (t = {value: void 0, left: void 0, right: void 0}, n){
t.value !== void 0
? t.value > n
? t.left = insertBinTree(t.left,n)
: t.right = insertBinTree(t.right,n)
: t.value = n;
return t;
}
return nodesList.reduce(f, void 0);
}
/**
* Fill a binary tree following breadth-first left to right order
*/
export function toBinaryTree(nodesList) {
const root = {
value: nodesList[0]
};
const nodesQueue = [root];
for (let i = 1; i < nodesList.length; i++) {
const nodeToFill = nodesQueue[0];
// If left is empty
if (nodeToFill.left?.value === undefined) {
nodeToFill.left = {
value: nodesList[i]
};
nodesQueue.push(nodeToFill.left);
continue;
}
// If right is empty
if (nodeToFill.right?.value === undefined) {
nodeToFill.right = {
value: nodesList[i]
};
nodesQueue.push(nodeToFill.right);
nodesQueue.shift();
continue;
}
}
return root;
}
/**
* Transform a tree in an array.
* The order of the elements follows the breadth first approach
* @param {*} root The root of the tree
* @returns A breadth first ordered list of node values
*/
export function treeToArray(root) {
const res = [];
const queue = [root];
while(queue.length !== 0) {
const node = queue.pop();
if (node) {
res.push(node.value);
queue.unshift(...[node.right, node.left])
}
}
return res;
}
/**
* Definition for singly-linked list.
* function ListNode(value, next) {
* this.value = (value===undefined ? 0 : value)
* this.next = (next===undefined ? null : next)
* }
*/
export function toLinkedList(list) {
let head = {};
let node = head;
for(let i in list) {
node.value = list[i];
if (i < list.length-1) {
const newNode = {};
node.next = newNode;
node = newNode;
}
}
return head;
}
export function linkedListToArray(linkedList) {
const result = [];
let head = linkedList;
while(head) {
result.push(head.value)
head = head.next;
}
return result;
}
export function arrayAreEquals(array1, array2) {
return array1.reduce((res, item, i) => res && array1[i] === array2[i] , true)
}
export function matrixAreEquals(matrix1, matrix2) {
return matrix1.reduce((res, item, i) => res && arrayAreEquals(matrix1[i], matrix2[i]) , true)
}