Tree DFS traversal using ES6 Generator

Using ES6 generator and iterator

by Yogesh Devatraj

HTML

<script>
  "use strict";
  var values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

  function constructTree(values) {
    return {
      dfs: function*(index) {
        if (!index) index = 0;
        yield values[index];
        //yield values[2 * index + 1]
        if ((2 * index + 1) < values.length)
          yield * this.dfs(2 * index + 1);
        if ((2 * index + 2) < values.length)
          yield * this.dfs(2 * index + 2);

      }
    }
  }

  function getDFSTraversal() {
    var tree = constructTree(values);
    var dfs = '';
    for (let val of tree.dfs()) {
      dfs = dfs + ' ' + val;
    }
    return dfs;
  }

</script>
<h1>Tree DFS traversal using ES6 Generator</h1>
<img src="http://algoviz.org/OpenDSA/Books/OpenDSA/html/_images/BinArray.png" style="height:200px; width:200px;" />
<h2>DFS : <script>document.write(getDFSTraversal())</script></h2>