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])
// ??
}
}
}
This is a solution using two stacks.
Suppose we always compute right child before left child, we need a way to store the result of right child. It's possible to store it on the original stack but it would be complicated since that stack is used to compute left child too. So I use another stack to store those results of right children.
There are three status:
When it sees a node with status
finish work
, it will check if the next node's status isneed merge
:finish work
What about something like this:
The call to get the same result would be
create(4);
. It is not exactly the same creation order, it creates the nodes from bottom to top, while recursive is like:You can also mimick this behavior with a stack:
The right node is pushed first on the stack and then the left node, so that the left node is higher in the stack and processed first.
Let's start with just the
i
s:There are so many ways we could use the iteratively generated order of
i
s; from pushing them all to an array, then following the trail of assignments backwards; to using thei
to create a new Klass and passing it by reference, essentially turning the process into top-down.It's not trivial to mechanically transform any recursive code into a stack machine. Automatic stateful transformations produce very complex code, just think of C#-s or BabelJS-s generators. But sure, it can be done, but you will need mutable stackframes and/or registers. Let's see the problems we are facing:
How does the machine remember where to continue the execution of a function?
We have to store some state variable/instruction pointer on the stack itself. This is what you are emulating with the
"open"
and"close"
markers.Where to put the result of a function?
There are many ways:
out
parametersUsing mutable stack frames and a result register the transformed code would look something like this: