-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTree.js
More file actions
69 lines (61 loc) · 1.94 KB
/
BinaryTree.js
File metadata and controls
69 lines (61 loc) · 1.94 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/
class BinaryTree {
constructor(val) {
this.val = val;
this.left = this.right = null;
}
static fromArray(array) {
// console.log("Tree.fromArray");
// console.log(array);
if (array == null || array.length == 0) return null;
const root = new BinaryTree(array.shift());
const queue = [root];
for (let layer = 1; array.length > 0; layer++) {
for (let i = 0; i < Math.pow(2, layer) / 2 && i < array.length; i++) {
const parent = queue.shift();
if (parent) {
const leftVal = array.shift();
const rightVal = array.shift();
parent.left = leftVal != undefined ? new BinaryTree(leftVal) : null;
parent.right = rightVal != undefined ? new BinaryTree(rightVal) : null;
queue.push(parent.left);
queue.push(parent.right);
}
}
}
return root;
}
static fromJson(json) {
console.log(json);
if (json.length == 0) {
return null;
}
const array = JSON.parse(json);
return BinaryTree.fromArray(array);
}
toArray() {
console.log(this);
if (!this) return "";
const output = [];
const queue = [this];
while (queue.length > 0) {
const node = queue.shift();
if (node != undefined) {
output.push(node.val);
queue.push(node.left);
queue.push(node.right);
}
else {
output.push(null);
}
}
while (output[output.length - 1] == undefined) {
output.pop();
}
return output;
}
toJson() {
return JSON.stringify(this.toArray());
}
};
exports.BinaryTree = BinaryTree;