function traverse(node, callback) { callback(node); if (node.children) node.children.forEach(child => traverse(child, callback)); }. Call the callback on the current node, then recurse into each child.
How do you traverse a tree recursively in JavaScript?
More FAQs in Recursive Problems and Solutions in JavaScript
function flatten(arr) { return arr.reduce((acc, item) => acc.concat(Array.isArray(item) ? flatten(item) : item), []); }. If an item is an array, recurse. Otherwise, concatenate.
function factorial(n) { if (n <= 1) return 1; return n * factorial(n - 1); }. Base case: 1 returns 1. Recursive case: n * factorial(n-1).
function reverse(str) { if (str.length <= 1) return str; return reverse(str.slice(1)) + str[0]; }. Take the first character, reverse the rest, and append the first character at the end.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.