我在 coffescript 中玩了一些算法,结果得到了一些意想不到的输出。这是我的代码:
traverse = (tree, stack) ->
stack.push tree.node
if not tree.branches
stack
else
traverse branch, stack for branch in tree.branches
one = { node: 1 }
two = { node: 2 }
tree = { node: "+", branches: [one, two] }
console.log traverse one, [] # => [ 1 ]
console.log traverse two, [] # => [ 2 ]
console.log traverse tree, [] # => [ [ '+', 1, 2 ], [ '+', 1, 2 ] ]
我希望在遍历时得到的输出tree
是[ '+', 1, 2 ]
,但这会被重复。我在这里错过了一些简单的事情吗?
谢谢。