Middle
How often have you worked with trees? What traversal algorithms do you know? What are the recursion limitations in JavaScript?
sobes.tech AI
Answer from AI
Trees are often encountered in tasks related to DOM structures, file systems, data hierarchies, etc. The main tree traversal algorithms are:
- Depth-First Search (DFS): includes three variants — preorder (node, then children), inorder (left child, node, right child, applicable to binary trees), postorder (children, then node).
- Breadth-First Search (BFS): level-by-level traversal starting from the root.
In JavaScript, recursion is limited by the call stack depth, which depends on the engine and usually amounts to a few thousand calls. Excessive recursion can cause a "Maximum call stack size exceeded" error. To avoid this, iterative algorithms with an explicit stack or recursion optimization (e.g., tail recursion if supported by the engine) can be used.
Example of depth-first traversal (preorder) in JavaScript:
function dfs(node) {
if (!node) return;
console.log(node.value); // process the node
node.children.forEach(child => dfs(child));
}
This approach is convenient for working with DOM or any hierarchical structures.