Skip to content

Instantly share code, notes, and snippets.

@tahmidsadik
Created July 25, 2018 08:36
Show Gist options
  • Save tahmidsadik/a7aaa3f7c1332dd21b0ab1e5883e8062 to your computer and use it in GitHub Desktop.
Save tahmidsadik/a7aaa3f7c1332dd21b0ab1e5883e8062 to your computer and use it in GitHub Desktop.
Dumbed down binary search tree, with only insert operation :)
let tree = { root: { val: null, left: null,
right: null
}
};
const createEmptySubtree = () => ({ val: null, left: null, right: null });
const insert = (node, root) => {
console.log(`node: ${node}, root: ${root}`);
if (!root.val) {
console.log("on root");
root.val = node;
} else if (node < root.val) {
// go left
if (!root.left) {
root.left = createEmptySubtree();
}
insert(node, root.left);
} else if (node > root.val) {
// go right
if (!root.right) {
root.right = createEmptySubtree();
}
insert(node, root.right);
}
};
insert(10, tree.root);
insert(50, tree.root);
insert(5, tree.root);
insert(29, tree.root);
console.log(tree);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment