Elliott de Launay
Elliott de Launay

Reputation: 1168

How can I apply recursion to a linked list that two levels deep?

I have the following method inside a model. That accepts a value and compares to an existing Set in a model:

function MyObj(set) = {
  this.set = new Set(set);
} 

MyObj.prototype.contains2Levels = function (target){
  let result = false; 
  let set = new Set(this.set);
  set.forEach(_id => {
    //goes one level deep
    if (_id == target || _id.set.has(target)) {
      result = true;
    } else {
      let set2 = new Set(_id.set);
      set2.forEach(_id2 => {
        if(_id2 == target || _id2.set.has(to)){
          result = true;
        }
      });
    }
  });
  return result;
}

I'm having a hard time understanding what the base case would be for a recursive loop that checks two levels down. This is as far as I get, but it's getting stuck when this is not present.

public contains2Levels(target){
  let result = false; 
  let arr = new Set(this.arr);

  //Unclear on what the base case would be...I keep getting into infinity loops.

  arr.forEach(_id => {
    //goes one level deep
    if (_id == target || _id.arr.has(target) || _id.contains2Levels(target)) {
      result = true;
    }
  });
  return result;
}

Upvotes: 0

Views: 43

Answers (1)

Sergio Rivas
Sergio Rivas

Reputation: 563

In general, when you want to cap the deep, you can add an argument with the current level and use it into the function...

function contains2Levels(target, level){
  ...
  contains2Levels(newTarget, level+1)....
  ...

  if (level==2) {
     // do something and do not call to the recursive function again
  }
}

// initial call
contains2Levels(initialTarget, 0);

Upvotes: 2

Related Questions