js如何获取tree型数组中当前项的最大深度呢?consttreeData=[{key:'tree1',children:[{key:'tree2',children:[{key:'tree3',children:[{key:'tree4'}]}]},{key:'tree5'}]},{key:'tree6'},{key:'tree7'}]想获得的结果console.log(getMaxDepthByKey('tree1',treeData))结果为3console.log(getMaxDepthByKey('tree2',treeData))结果为2console.log(getMaxDepthByKey('tree3',treeData))结果为1console.log(getMaxDepthByKey('tree4',treeData))结果为0console.log(getMaxDepthByKey('tree5',treeData))结果为0console.log(getMaxDepthByKey('tree6',treeData))结果为0console.log(getMaxDepthByKey('tree7',treeData))结果为0
2 回答
牧羊人nacy
TA贡献1862条经验 获得超7个赞
经典的深度优先搜索,只有一个数据么,如果是的话,可以预处理下:letans={}functiongetMaxDepthByKey(treeData){for(letitemoftreeData){getDepth(item)}functiongetDepth(obj){if(obj.hasOwnProperty('children')){ans[obj.key]=0for(letitemofobj.children)ans[obj.key]=Math.max(ans[obj.key],getDepth(item)+1)returnans[obj.key]}else{ans[obj.key]=0return0}}}getMaxDepthByKey(treeData)console.log(ans['tree1'])//3console.log(ans['tree2'])//2console.log(ans['tree3'])//1console.log(ans['tree4'])//0console.log(ans['tree5'])//0console.log(ans['tree6'])//0console.log(ans['tree7'])//0但是题主对调用方式做了固定,稍微改下即可
Helenr
TA贡献1780条经验 获得超4个赞
参照楼上的修改了一下,嘻嘻vardeep=0;functiongetMaxDepthByKey(str,data){for(vari=0;iif(str===data[i].key){ deep=getDeep(data[i]);break;}else{if(data[i].hasOwnProperty('children')){getMaxDepthByKey(str,data[i].children);}}}returndeep;}varmaxLen=[];functiongetDeep(data){if(data.hasOwnProperty('children')){maxLen[data.key]=0;for(letitemofdata.children)maxLen[data.key]=Math.max(maxLen[data.key],getDeep(item)+1);returnmaxLen[data.key];}else{return0;}}console.log(getMaxDepthByKey('tree1',treeData));//3console.log(getMaxDepthByKey('tree2',treeData));//2console.log(getMaxDepthByKey('tree3',treeData));//1console.log(getMaxDepthByKey('tree4',treeData));//0console.log(getMaxDepthByKey('tree5',treeData));//0console.log(getMaxDepthByKey('tree6',treeData));//0console.log(getMaxDepthByKey('tree7',treeData));//0
添加回答
举报
0/150
提交
取消