-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathbinary_tree.ts
50 lines (39 loc) · 1.04 KB
/
binary_tree.ts
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
export interface BinaryTreeNode<T> {
val: T;
left: BinaryTreeNode<T> | null;
right: BinaryTreeNode<T> | null;
}
export function createBinaryTreeNode<T>(
array: (T | null)[]
): BinaryTreeNode<T> | null {
if (array.length === 0) return null;
let skipped = 0;
const root = { val: array[0]!, left: null, right: null };
const queue: [number, BinaryTreeNode<T>, BinaryTreeSide][] = [
[1, root, BinaryTreeSide.left],
[2, root, BinaryTreeSide.right]
];
while (queue.length >= 1) {
const [index, parent, side] = queue.shift()!;
if (index >= array.length) break;
if (array[index] === null) {
skipped += 1;
continue;
}
const node = { val: array[index]!, left: null, right: null };
if (side === BinaryTreeSide.left) {
parent.left = node;
} else {
parent.right = node;
}
queue.push(
[(index - skipped) * 2 + 1, node, BinaryTreeSide.left],
[(index - skipped) * 2 + 2, node, BinaryTreeSide.right]
);
}
return root;
}
enum BinaryTreeSide {
left,
right
}