【发布时间】:2014-04-17 07:08:44
【问题描述】:
我知道这是基本的计算机科学问题,我的问题可能匹配的是this。
但它没有涵盖我的 web 应用程序中的两种不同场景。
我正在处理两个不同的树状对象数组,它们以children 作为成员。
现在
具有固定高度的第一棵树(最多 3 层)
第二棵树,具有任意级别深度。
两棵树的结构类似于下面(它是一个对象数组,基本上是一个 JSON):
0 ---- someKey
|
---- someOtherKey
|
---- children
0 ---- someKey
|
---- someOtherKey
|
---- children
0 ---- someKey
|
---- someOtherKey
|
---- children []
1 ---- someKey
|
---- someOtherKey
|
---- children []
1 ---- someKey
|
---- someOtherKey
|
---- children []
2 ---- someKey
|
---- someOtherKey
|
---- children []
现在要遍历第一棵树,我使用 3 个嵌套的 for 循环,而对于第二个,我使用递归来访问每个节点直到叶子。到目前为止,我的表现还算公平。
但是在第一种情况下使用递归有什么好处吗?
或
如果第二棵树的深度可变,递归在哪里会不足?
【问题讨论】:
标签: javascript recursion tree iteration