Skip to content

Instantly share code, notes, and snippets.

@tomgullo
Created August 5, 2013 23:56
Show Gist options
  • Save tomgullo/6160746 to your computer and use it in GitHub Desktop.
Save tomgullo/6160746 to your computer and use it in GitHub Desktop.
use stack in place of recursion
function node(name, parent) {
return {
name:name,
parent:parent
}
}
root = node('root')
n2 = node('left', root)
root.left = n2
n3 = node('2left', n2)
n2.left = n3
n4 = node('right', root)
root.right = n4
n5 = node('3left', n3)
n3.left = n5
function size(nodz) {
if (!nodz) return 0;
return 1 + size(nodz.left) + size(nodz.right);
}
var stack = [root]
var ctr = 1;
function iter(list){
do {
ctr++
var node = stack.shift()
if (node.left) {
stack.push(node.left)
} else if (node.right) {
stack.push(node.right)
}
} while (stack.length > 0)
}
iter(stack);
console.log(new Date() + " " + ctr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment