Given the following algorithm:
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
}
It creates the Klass in create(0) last, after creating all the children, recursively. So it creates the leaf nodes first, then passes that up to the parent, etc.
Wondering how to do this using a stack without recursion. Making my head hurt :). I understand how to use a stack to create from the top-down, but not the bottom up. For top-down, it's essentially this:
var stack = [0]
while (stack.length) {
var i = stack.pop()
// do work
stack.push(children)
}
From the bottom up, I can't see how it should work. This is where I get stuck:
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])
// ??
}
}
}