Given the following algorithm:
What about something like this:
console.log(JSON.stringify(create(4), null, 2))
function create(depth) {
let n = Math.pow(2, depth);
let nodes = [];
for (let i = 0; i < n; i++)
nodes.push(new Klass(depth));
for (depth--; depth >= 0; depth--) {
let next = [];
while (nodes.length > 0)
next.push(new Klass(depth, nodes.pop(), nodes.pop()));
nodes = next;
}
return nodes[0];
}
function Klass(i, l, r) {
this.i = i
this.l = l
this.r = r
}
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:
7
3 6
1 2 4 5
You can also mimick this behavior with a stack:
console.log(JSON.stringify(create(4), null, 2))
function create(depth) {
let stack = [{depth: 0}]
for (;;) {
let i = stack.length - 1
let cur = stack[i]
if (typeof cur.left === 'undefined') {
if (cur.depth < depth) {
stack.push({depth: cur.depth + 1, parent: i, pos: 'right'})
stack.push({depth: cur.depth + 1, parent: i, pos: 'left'})
} else {
stack[cur.parent][cur.pos] = new Klass(cur.depth)
stack.pop()
}
} else {
let node = new Klass(cur.depth, cur.left, cur.right)
if (cur.depth == 0)
return node
stack[cur.parent][cur.pos] = node
stack.pop()
}
}
}
function Klass(i, l, r) {
this.i = i
this.l = l
this.r = r
}
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.