Tree Traversal (DFS & BFS)
Tree Traversal (DFS & BFS) is a reusable JavaScript snippet. Traverses a tree data structure using Depth-First Search or Breadth-First Search. Works with nested objects and DOM trees. The full implementation: // Depth-First Search (DFS) function dfs(tree, childrenKey = 'children') { const result = [] function walk(node) { result.push(node) if (node[childrenKey]) { for (const child of node[childrenKey]) walk(child) } } walk(tree) return result } // Breadth-First Search (BFS) function bfs(tree, childrenKey = 'children') { const result = [] const queue = [tree] while (queue.length) { const node = queue.shift() result.push(node) if (node[childrenKey]) queue.push(...node[childrenKey]) } return result } // Find in tree (DFS) function findInTree(tree, predicate, childrenKey = 'children') { if (predicate(tree))… This snippet uses only standard JavaScript with no dependencies, so it runs in modern browsers and Node.js alike. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.