Breadth First Search
Breadth-first search is an algorithm for traversing or searching tree or graph data structures, exploring all neighbor nodes at the present depth before moving to nodes at the next depth level.
Example in TypeScript
function breadthFirstSearch(root: SearchNode): void {
const queue = [root];
while (queue.length > 0) {
const current: any = queue.shift();
console.log(current.value);
for (const child of current.children) {
queue.push(child);
}
}
}
class SearchNode {
value: string;
children: SearchNode[];
constructor(value: string, children: SearchNode[]) {
this.value = value;
this.children = children;
}
}Usage
Last updated