Facebook Pixel

Recursion for Tree Traversal in JavaScript

How to use recursion for tree traversal (DFS, file systems, DOM).

Recursion for Tree Traversal in JavaScript

Trees are naturally recursive: each node has children, which are themselves trees.

File System

function listFiles(node, depth = 0) { console.log(" ".repeat(depth) + node.name); if (node.type === "folder" && node.children) { node.children.forEach(child => listFiles(child, depth + 1)); } }

DOM Traversal

function walkDOM(node, callback) { callback(node); if (node.children) { Array.from(node.children).forEach(child => walkDOM(child, callback)); } } walkDOM(document.body, (node) => console.log(node.tagName));

JSON Exploration

function findKeys(obj, targetKey, results = []) { Object.keys(obj).forEach(key => { if (key === targetKey) results.push(obj[key]); if (typeof obj[key] === "object" && obj[key] !== null) { findKeys(obj[key], targetKey, results); } }); return results; }

Binary Tree Traversal

function inorder(node) { if (!node) return; inorder(node.left); console.log(node.value); inorder(node.right); }

The Takeaway

Tree traversal with recursion: file systems (recurse on children), DOM (recurse on childNodes), JSON (recurse on object properties), and binary trees (inorder: left, root, right). Trees are naturally recursive data structures.

function traverse(node) { callback(node); if (node.children) node.children.forEach(child => traverse(child)); }. Process the current node, then recurse into each child. The base case is implicit (no children = no recursion).

function walkDOM(node, callback) { callback(node); Array.from(node.children).forEach(child => walkDOM(child, callback)); }. Call the callback on the current node, then recurse into each child element.

function inorder(node) { if (!node) return; inorder(node.left); console.log(node.value); inorder(node.right); }. Visit left subtree, then root, then right subtree. Returns values in sorted order for a BST.

function findKeys(obj, target, results = []) { Object.keys(obj).forEach(key => { if (key === target) results.push(obj[key]); if (typeof obj[key] === 'object') findKeys(obj[key], target, results); }); return results; }

Because each node in a tree is itself a tree (a subtree). The children of a node are trees. This self-similar structure makes recursion the natural approach for traversal, search, and manipulation.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.