Search code examples
recursiondata-structurestreedepth-first-search

DFS in Tree data structure - What is the base case here in this recursive function?


(I'm not native speaker. I apologize for my poor English😿)

If there is a tree like below.

enter image description here

Each node is an object.

ex) nodeA.data = 23, nodeA.children = [nodeB, nodeC]

If we search this tree in DFS from the root, the result will be

23 - 19 - 15 - 22 - 35 - 31 - 38

and the code below is an implementation of DFS, which successfully logs the same result as above.

class TreeNode {
  constructor(data) {
    this.data = data;
    this.children = [];
  }
  
  // ... omit  

  depthFirstTraversal() {
    console.log(this.data);
    this.children.forEach(child => child.depthFirstTraversal());
  }
}

But I'm curious :

What if the recursive call inside the forEach loop is repeated and finally "child" parameter points to nodeD?

enter image description here


Solution

  • The situation you fear for will not happen.

    The child variable in the forEach callback could only be undefined if in a children array you have undefined values. But that would be an odd thing to do. In reality, when this is a leaf node (like node D), it will have an empty this.children array, and so the forEach loop will not make any iterations, and its callback function will not be called.

    That is where the base case of the recursion is realised: when this.children.length == 0.