Skip to content

Instantly share code, notes, and snippets.

@idiglove
Created January 26, 2024 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save idiglove/a3694d96f046d02bb755afc404fda52f to your computer and use it in GitHub Desktop.
Save idiglove/a3694d96f046d02bb755afc404fda52f to your computer and use it in GitHub Desktop.
cassidoo algo practice - Write a data structure for a simple binary tree, and a function that prints a given tree.
class Node {
value = null;
left = null;
right = null;
constructor(value) {
this.value = value;
}
printBothNodes(right, left, lastNodeVal) {
const { value: leftVal } = left;
const { value: rightVal } = right;
let toPrint = "";
Array(lastNodeVal - 1)
.fill(null)
.forEach(() => {
toPrint += " ";
});
console.log(`${toPrint}${leftVal} ${rightVal}`);
this.printNodes(left, lastNodeVal - 1, true);
this.printNodes(right, lastNodeVal - 1, true);
}
printNodes(node, lastNodeVal, isDeep) {
const { value, left, right } = node ?? {};
// leaf nodes
if (left === null && right === null) {
return;
}
// has both nodes
if (left !== null && right !== null) {
if (!isDeep) {
// root
let toPrint = "";
Array(lastNodeVal)
.fill(null)
.forEach(() => {
toPrint += " ";
});
toPrint += value;
console.log(toPrint);
}
// print branches
let toPrintBranch = "";
Array(lastNodeVal - 1)
.fill(null)
.forEach(() => {
toPrintBranch += " ";
});
console.log((toPrintBranch += "/ \\"));
this.printBothNodes(right, left, lastNodeVal - 1);
return;
}
}
}
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.printNodes(root, 5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment