Skip to content

Instantly share code, notes, and snippets.

@AbeEstrada
Last active September 3, 2025 00:19
Show Gist options
  • Save AbeEstrada/d537541013ee378f0e702880f6c0b5fd to your computer and use it in GitHub Desktop.
Save AbeEstrada/d537541013ee378f0e702880f6c0b5fd to your computer and use it in GitHub Desktop.
Exercise: Binary Search Tree Insertion
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
function insert(root, data) {
if (root === null) {
return new Node(data);
}
if (data < root.data) {
root.left = insert(root.left, data);
} else if (data > root.data) {
root.right = insert(root.right, data);
}
return root;
}
function createBST(values) {
let root = null;
for (let value of values) {
root = insert(root, value);
}
return root;
}
function preOrder(root) {
const result = [];
function traverse(node) {
if (node === null) return;
result.push(node.data);
traverse(node.left);
traverse(node.right);
}
traverse(root);
return result;
}
function processData(input) {
const lines = input.trim().split("\n");
const values = lines[1].split(" ").map(Number);
const root = createBST(values);
console.log(preOrder(root).join(" "));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment