MCPcopy Create free account
hub / github.com/betomoedano/JavaScript-Coding-Interview-Questions / BinaryTree

Class BinaryTree

binary-trees/branch-sums.js:1–26  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class BinaryTree {
2 constructor(value) {
3 this.value = value;
4 this.left = null;
5 this.right = null;
6 }
7 insert(values, i = 0) {
8 if (i >= values.length) return;
9 const queue = [this];
10 while (queue.length > 0) {
11 let current = queue.shift();
12 if (current.left === null) {
13 current.left = new BinaryTree(values[i]);
14 break;
15 }
16 queue.push(current.left);
17 if (current.right === null) {
18 current.right = new BinaryTree(values[i]);
19 break;
20 }
21 queue.push(current.right);
22 }
23 this.insert(values, i + 1);
24 return this;
25 }
26}
27
28// time O(n) where n is the number of nodes
29// space O(n)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected