避免树行走递归的最佳方法

时间:2012-01-13 14:32:46

标签: javascript recursion

所以我对javascript很新,我试图为朋友写一个特殊的班次调度代码。目前的工作方式如下:

function walk(currentDay) {
    var today = allWorkDays[currentDay]; // An array of all workdays we need to schedule
    var vertices = fetchCombinationsForToday(today); // Fetch an array of 0 length or more
                                                // containing possibilities for the day
                                                // according to rules set by user
    for (var i=0; i<vertices.length; i++) {
         [we add the vertices[i] to a running array]
         walk(currentDay+1);
    }
    if (currentDay == sumOfAllDays) { // We are at a leaf
           analyzeSchedule(); // This will keep a copy of the current schedule 
                              // if it has a higher score than X
    }
    [some business to pop the last node/day we added to our global array]
}

现在,评论中指定的规则是通常分析最后5-10个最后添加的元素(天)的规则,并返回今天可能的变化。

我在这里遇到的问题是,我希望程序能够提供超过一千天的数组计划,但由于递归,我会超出函数调用限制。有没有办法在不使用javascript中的递归的情况下走树?我似乎无法找到一个,尽管大多数人说通过递归可以解决的问题可以通过循环解决,反之亦然。

请记住,顶点数组在树的早期很大(20-30个元素)但很快变小(0-5个元素)。我从来没有运行过这段代码[编辑:并且得到了一个“函数调用限制达到”的错误]顺便说一下,这就是所有的理论[编辑:我现在会达到它的事实]。

1 个答案:

答案 0 :(得分:1)

JavaScript Arrays提供了推送/弹出和移位/取消移动开始和结束值的方法,因此您可以像队列一样使用它们。例如:

var a = [0, 1, 2];
a.push(3); // => 3
a; // [0, 1, 2, 3]
a.shift(); // => 0
a; // [1, 2, 3]
a.pop(); // => 3
a; // [1, 2]

通过这种方式,您可以通过推送和弹出/取消从数组中移动来构建树结构并跟踪要访问的节点。