根据如下树的结构,写出数的深度遍历与广度遍历
const tree = {
val:'a',
children:[
{
val:'b',
children:[
{val:'d',children:[]},
{val:'e',children:[]},
]
},
{
val:'c',
children:[
{val:'f',children:[]},
{val:'g',children:[]}
]
}
]
}
1.深度遍历
const fun1=(root)=>{
if(root===null) return;
let p=root;
if(p){
console.log(p.val);
for(let i=0;i<p.children.length;i++){
fun1(p.children[i]);
}
}
}
2.广度遍历
const fun2=(root)=>{
let arr=[];
let res=[];
if(root===null) return root;
arr.push(root);
while(arr.length!==0){
let p=arr.shift();
res.push(p.val);
arr.push(...p.children);
}
return res;
}