Skip to content

Instantly share code, notes, and snippets.

@shovon
Last active July 23, 2025 06:29
Show Gist options
  • Save shovon/61bac3e6fad7f29a28ffd73a635d25ff to your computer and use it in GitHub Desktop.
Save shovon/61bac3e6fad7f29a28ffd73a635d25ff to your computer and use it in GitHub Desktop.
A graph represented using an associative array, keyed by the number, and an array key-value pair
type Graph<K, V> = Map<K, [K, V][]>;
type BinaryTreeNode<T> = {
left?: [T] | null | undefined;
right?: [T] | null | undefined;
};
type BinaryTree<K> = Map<K, BinaryTreeNode<K>>;
const bst: BinaryTree<number> = new Map();
function insert(
graph: BinaryTree<number>,
{ root, toInsert }: { root: number; toInsert: number }
) {
const value = graph.get(root);
if (!value) {
graph.set(toInsert, {});
} else {
if (toInsert < root) {
if (!value.left) {
value.left = [toInsert];
graph.set(toInsert, {});
} else {
insert(graph, { root: value.left[0], toInsert });
}
} else if (toInsert > root) {
if (!value.right) {
value.right = [toInsert];
graph.set(toInsert, {});
} else {
insert(graph, { root: value.right[0], toInsert });
}
}
}
}
function* traverse(graph: BinaryTree<number>, root: number) {
const node = graph.get(root);
if (node) {
if (node.left) {
yield* traverse(graph, node.left[0]);
}
yield root;
if (node.right) {
yield* traverse(graph, node.right[0]);
}
}
}
insert(bst, { root: 1, toInsert: 1 });
insert(bst, { root: 1, toInsert: 2 });
insert(bst, { root: 1, toInsert: 50 });
insert(bst, { root: 1, toInsert: 45 });
insert(bst, { root: 1, toInsert: 30 });
insert(bst, { root: 1, toInsert: 10 });
console.log([...traverse(bst, 1)]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment