Recursive function to browse a tree with controlled depth in Javascript
<p>I have a data structure that is composed of tree. each parent holds 3 children. I want to create a recursive function in javascript (specially for node.js) that will browse that tree completely until it reaches a depth defined (let's assume the depth is 3 here).
So I've written this function :</p>

<pre><code> var i=0;
function recursive (depth) {
    console.log("total = "+ i++);
    console.log("the depth is "+ depth)
    if (depth&gt;3){return} else
        {depth++;
            for (j = 1; j &lt;= 3; j++){
                recursive(depth);
            };
        }
    }

    recursive(0);
</code></pre>

<p>Now form the output of this program, I guess my function browses the first branch and when it reaches the depth, scans the 3 children and returns. But I want it to scan the other children so the total of nodes reached should be 1 + 3 + 9 = 13 and not 6 that is shown in my total.</p>

<p>Can you help me with this please?</p>