【发布时间】:2018-06-27 02:17:13
【问题描述】:
给定以下算法:
console.log(JSON.stringify(create(0), null, 2))
function create(i) {
if (i == 5) return
return new Klass(i, create(i + 1), create(i + 1))
}
function Klass(i, l, r) {
this.i = i
this.l = l
this.r = r
}
它在create(0) 中创建Klass last,在创建所有孩子之后,递归地。所以它首先创建叶节点,然后将其传递给父节点,等等。
想知道如何使用没有递归的堆栈来做到这一点。让我头疼:)。我了解如何使用堆栈从自上而下创建,而不是自下而上。对于自上而下,本质上是这样的:
var stack = [0]
while (stack.length) {
var i = stack.pop()
// do work
stack.push(children)
}
自下而上,我看不出它应该如何工作。这就是我卡住的地方:
function create(i) {
var stack = []
stack.push([i, 'open'])
stack.push([i, 'close'])
while (stack.length) {
var node = stack.pop()
if (node[1] == 'open') {
stack.push([ node[0] + 1, 'open' ])
stack.push([ node[0] + 1, 'close' ])
} else {
// ?? not sure how to get to this point
var klass = new Klass(node[0], node[2], node[3])
// ??
}
}
}
【问题讨论】:
-
只是一个指针,循环和推送到同一个数组可能对健康有害!如果你反转最初的插入,它可能会变成一个永无止境的循环。
标签: javascript algorithm recursion iteration