Sobes.tech
Middle

How to avoid call stack overflow when traversing a tree? How to implement iterative traversal using a stack in JavaScript?

sobes.tech AI

Answer from AI

To avoid call stack overflow when traversing a tree, an iterative traversal with an explicit stack is used instead of a recursive approach.

Example of iterative tree traversal in JavaScript (depth-first traversal):

function iterativeDFS(root) {
  const stack = [root];
  while (stack.length > 0) {
    const node = stack.pop();
    console.log(node.value); // process the node
    // Add children to the stack (for example, right to left, so that left is processed first)
    for (let i = node.children.length - 1; i >= 0; i--) {
      stack.push(node.children[i]);
    }
  }
}

This approach allows controlling the stack depth manually and prevents overflow, which can occur with deep recursion.