Last active
July 23, 2025 06:29
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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