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;
};
以上代码有效并返回二叉树中的节点数。
我对它的工作原理感到困惑。 var stack = [];
不会创建一个空数组吗?
如果是这样,当在 for 循环中设置时节点不会变为 0,从而使两个 if 语句都返回 false 并且不运行吗?
编辑: 我刚刚意识到代码 node = stack.pop()
直到循环体结束时才会执行。因此,直到该点的节点将包含传递到过程中的当前节点(从头节点开始)。
为这个平凡的问题道歉,我想该 sleep 了
最佳答案
您可以将其重写为:
var count = function(tree) {
var stack = [];
var count = 0;
var node = tree; // set node to the tree (the tree's root node)
while (node) { // while the node is not null
// The way these pushes are done, it's basically doing a depth first search
if (node.left) stack.push(node.left);
if (node.right) stack.push(node.right);
count++;
node = stack.pop();
}
return count;
};
换句话说,node
在运行时不会变为零,因为stack
是空的。它被设置为 tree
,而不是 stack
。 You can see it work here .
关于javascript - 不确定这个片段是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12433704/