Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Last active Mar 8, 2021
Embed
What would you like to do?
class Node {
constructor(value, left = null, right = null) {
this.value = value;
this.left = left;
this.right = right;
}
find(value) {
let current = this;
while (true) {
if (value === current.value) {
return true;
} else if (value > current.value && current.right) {
current = current.right;
} else if (value < current.value && current.left) {
current = current.left;
} else {
break;
}
}
return false;
}
insert(value) {
let current = this;
while (true) {
if (value === current.value) {
throw new Error("Do not insert duplicate values");
} else if (value > current.value) {
if (!current.right) {
current.right = new Node(value);
break;
}
current = current.right;
} /* if (value < current.value) */ else {
if (!current.left) {
current.left = new Node(value);
break;
}
current = current.left;
}
}
}
toString() {
let levels = [];
let queue = [this];
while (queue.length) {
const previousQueue = [...queue];
const values = previousQueue.map((item) => (item ? item.value : null));
if (values.some((v) => v !== null)) {
levels.push(values);
} else {
break;
}
queue = [];
for (const item of previousQueue) {
if (item) {
queue.push(item.left, item.right);
} else {
queue.push(null, null);
}
}
}
const WHITESPACE = " ";
const MISSING = " ";
const getWidth = (values, levelsCount) =>
values.reduce(
(acc, v, i) => acc + WHITESPACE.length + (v ? String(v).length : 0),
0
);
const maxWidth = levels.reduce(
(max, values) => Math.max(max, getWidth(values, levels.length)),
0
);
let output = "";
for (let i = 0; i < levels.length; i++) {
const level = levels[i];
const start = Math.floor(maxWidth / 2) - WHITESPACE.length * (2 * i);
const line = WHITESPACE.repeat(start);
output +=
line +
level
.map((v) => (v ? v : MISSING))
.join(WHITESPACE.repeat(levels.length - i)) +
"\n\n";
}
return output;
}
}
const root = new Node(11);
root.insert(6);
root.insert(10);
root.insert(7);
root.insert(12);
root.insert(3);
root.insert(16);
root.insert(18);
root.insert(9);
console.log(root);
console.log(root.toString());
@sebinsua
Copy link
Author

sebinsua commented Mar 6, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment