-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
81 lines (67 loc) · 1.39 KB
/
index.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
'use strict';
function ListNode(val) {
this.val = val;
this.next = null;
}
function createList(arr) {
var head = new ListNode();
var current = head;
arr.forEach(function (item) {
current.next = new ListNode(item);
current = current.next;
});
return head.next;
}
ListNode.prototype.toArray = function () {
return toArray(this);
}
function toArray(node) {
var ans = [];
while(node) {
ans.push(node.val)
node = node.next;
}
return ans;
}
exports.List = {
node: ListNode,
create: createList,
toArray: toArray
};
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
// create Tree from array
// https://leetcode.com/faq/#binary-tree
function createTree(arr) {
if (!arr.length || arr[0] === null) return null;
var res = new TreeNode(arr[0]);
var nodes = arr.slice(1);
var children = [res];
while(children.length) {
let current = children.shift();
if (!current || current.val === null) {
continue;
}
if (nodes.length) {
let val = nodes.shift();
if (val) {
current.left = new TreeNode(val);
children.push(current.left);
}
}
if (nodes.length) {
let val = nodes.shift();
if (val) {
current.right = new TreeNode(val);
children.push(current.right);
}
}
}
return res;
}
exports.Tree = {
node: TreeNode,
create: createTree,
};