Trees & Graphs
Binary Trees
Each node has at most two children.
class TreeNode<T> {
value: T;
left: TreeNode<T> | null = null;
right: TreeNode<T> | null = null;
constructor(value: T) {
this.value = value;
}
}
Tree Traversals
// In-order (Left, Root, Right)
function inOrder<T>(node: TreeNode<T> | null, result: T[] = []): T[] {
if (!node) return result;
inOrder(node.left, result);
result.push(node.value);
inOrder(node.right, result);
return result;
}
// Pre-order (Root, Left, Right)
function preOrder<T>(node: TreeNode<T> | null, result: T[] = []): T[] {
if (!node) return result;
result.push(node.value);
preOrder(node.left, result);
preOrder(node.right, result);
return result;
}
Graphs
Graphs consist of vertices (nodes) connected by edges.
class Graph {
private adjacencyList = new Map<string, string[]>();
addVertex(vertex: string): void {
if (!this.adjacencyList.has(vertex)) {
this.adjacencyList.set(vertex, []);
}
}
addEdge(v1: string, v2: string): void {
this.adjacencyList.get(v1)?.push(v2);
this.adjacencyList.get(v2)?.push(v1);
}
bfs(start: string): string[] {
const visited = new Set<string>();
const queue = [start];
const result: string[] = [];
visited.add(start);
while (queue.length > 0) {
const vertex = queue.shift()!;
result.push(vertex);
for (const neighbor of this.adjacencyList.get(vertex) || []) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
return result;
}
}