title: Traversing graph using while loop iteration
body: <p>I am using <code>cytoscape.js</code> to create a graph.</p>
  
  <p>I want to travel through the nodes (with direction), but only to those nodes who are connected with a edge that contains a specific value.</p>
  
  <p>I have done it with recursion like this</p>
  
  <pre><code>function traverse(node, requiredValue, visitedNodes) {
    // break if we visit a node twice
    if (visitedNodes.map(visitedNode =&gt; visitedNode.id()).includes(node.id())) {
      return visitedNodes;
    }
  
    // add visited node to collection
    visitedNodes.push(node);
  
    // select node
    node.select();
  
    // only travel through valid edges
    const edgesTo = node.outgoers(function () {
      return this.isEdge() &amp;&amp; this.data('requiredValues').includes(requiredValue);
    });
  
    // break if no valid connected edges
    if (edgesTo.empty()) {
      return visitedNodes;
    }
  
    // travel through edges
    edgesTo.forEach(edge =&gt; {
      edge.select()
      return traverse(edge.target(), agent, visitedNodes);
    });
  }
  </code></pre>
  
  <p>It seems to work, but I am not very good at algorithms, so I am not sure if this is a clever way to build it. I have read a bit about breadth first and depth first search algorithms, but I am not sure if it's those algorithms that I need.</p>
  
  <p>Would it be possible to traverse a tree without using recursion? I have also tried with a <code>while</code> loop, but since it is a tree, I don't think I can just use</p>
  
  <pre><code>node = rootNode;
  
  while (true) {
    // find leaving edges
    ...
  
    edgesTo.forEach(edge =&gt; {
      // set new node to traverse
      node = edge.target;
    }
  }
  </code></pre>
  
  <p>since I guess the <code>edgesTo.forEach()</code> will finish before moving on to the next iteration in the <code>while</code> loop. I need it to traverse 'simultaneously' through the different branches.</p>
  
  <p>I can see from <a href="http://js.cytoscape.org/#collection/algorithms" rel="nofollow">http://js.cytoscape.org/#collection/algorithms</a> that the library has multiple algorithms (including bfs and dfs), but do I need those algorithms when I want to traverse the tree without the purpose of searching for one specific node?</p>