当前位置: 首页 > Web前端 > HTML5

面试题:给你一个id,去取名字,多叉树遍历

时间:2023-04-06 00:07:51 HTML5

前天面试的时候遇到一道多叉树面试题,所以在这里分享记录一下。题目:一个树形的数据(数据如下),面试官会给你一个id,然后得到对应的名字?数据结构大概是这样的varcityData=[{id:1,name:'广东省',children:[{id:11,name:'深圳',children:[{id:111,name:'宝安',children:[{id:1111,name:'西乡',children:[{id:11111,name:'彭州',children:[]},{id:11112,name:'灵芝',children:[]}]},{id:1112,name:'南山',children:[{id:11121,name:'科技园',children:[]}]}]},{id:112,name:'福田',children:[]}]},{id:12,name:'广州',children:[{id:122,name:'白云区',children:[{id:1222,name:'白云区',children:[]}]},{id:122,name:'珠海区',children:[]}]}]},{id:2,name:'湖南省',children:[]}];比如我要id为11112的名字返回灵芝,你有几种解法??递归方法的题目让人看出来这是一个递归方法,代码如下letresult=''//递归实现constrecursion=(cityData,id)=&g吨;{//当cityData数据为空时,直接返回if(!cityData||!cityData.length)return;//常规循环cityDatafor(leti=0,len=cityData.length;i0){递归(childs,id);}}returnresult};constr=recursion(cityData,11112);console.log(r)//灵芝呀~~~完成了吗??面试官可能不满意,下面有几个方案广度优先实现letresult=''constrange=(cityData,id)=>{if(!cityData||!cityData.length)return;//定义一个数据栈letstack=[];让项目=空;//将第一层节点先入栈for(vari=0,len=cityData.length;i{//直接返回如果没有数据if(!cityData||!cityData.length)return;//先定义一个数据栈letstack=[]letitem=null//先放入第一层将节点放入数据栈for(vari=0,len=cityData.length;i{//没有数据直接返回if(!cityData||!cityData.length)返回;//将数据转换为字符串letcityStr=JSON.stringify(cityData)//定义正则性letreg=newRegExp(`"id":${id},"name":"([^\\x00-\\xff]+)",`)//获取正则子串并返回return(cityStr.match(reg))[1]}letr4=regular(cityData,11112);console.log(r4)//这里灵芝列举了4个方法,应该还有很多方法,大佬们有的话想留言的先谢谢啦~~安利博客~~~https://github.com/naihe138/naice-blog