I have the json tree below.
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: [],
},
]
}
],
},
]
}
How to traverse the tree by Level?
In other words, if the applied function on each node is just console.log
The above input should print 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14
or even better, we can print by level and the output would be:
Level 0: [0]
Level 1: [1,2,3]
LeveL 2: [4,5,6,7,8]
Level 3: [9,10,11,12,13,14]
Failed Attempt
function walkTree(t){
console.log(t.v);
for(const child of t.c){
walkTree(child)
}
}