【发布时间】:2021-01-03 07:33:55
【问题描述】:
我有下面的 json 树。
interface Tree {
v: number, // value
c: Tree[], // children
}
const tree: Tree = {
v: 0, c: [
{
v: 1,
c: [
{
v: 4,
c: [
{
v: 9, c: [],
}
],
},
{
v: 5,
c: [
{
v: 10, c: [],
}
],
},
],
},
{
v: 2,
c: [
{
v: 6,
c: [
{
v: 11, c: [],
}
],
},
{
v: 7,
c: [
{
v: 12, c: [],
}
],
}
],
},
{
v: 3,
c: [
{
v: 8,
c: [
{
v: 13, c: [],
},
{
v: 14, c: [],
},
]
}
],
},
]
}
如何按Level遍历树?
也就是说,如果每个节点上应用的函数只是console.log
上面的输入应该打印 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14
甚至更好,我们可以逐层打印,输出将是:
Level 0: [0]
Level 1: [1,2,3]
LeveL 2: [4,5,6,7,8]
Level 3: [9,10,11,12,13,14]
尝试失败
function walkTree(t){
console.log(t.v);
for(const child of t.c){
walkTree(child)
}
}
【问题讨论】:
-
你有没有尝试过什么具体的东西?
-
我试过的递归函数。但它通过分支而不是级别遍历
-
向我们展示递归函数。这应该是正确的方法,但可能是您的实施失败了。
-
function walkTree(t){ console.log(t.v); for(const child of t.c){ walkTree(child) } }
标签: javascript algorithm data-structures tree