var count = function(tree) {
var stack = [];
var count = 0;
for (var node = tree; node; count++, node = stack.pop()) {
if (node.left) stack.push(node.left);
if (node.right) stack.push(node.right);
}
return count;
};
The above code works and returns the count of nodes within a binary tree.
I am confused as to how this works. Does var stack = []; not create an empty array?
If so, does node not become 0 when set within the for loop, thus making both if statements return false and not run?
EDIT: I just realised the code node = stack.pop() will not be executed until the end of the loop body. Therefore node until that point will contain the current node passed into the procedure (Beginning with the head node).
Apologies for the mundane question, it’s time for bed I think
You can rewrite it as:
In other words,
nodedoes not become zero when it is run becausestackis empty. It is set totree, notstack. You can see it work here.