js如何获取tree型数组的最大深度呢?

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))结果为3
console.log(getMaxDepthByKey('tree2',treeData))结果为2
console.log(getMaxDepthByKey('tree3',treeData))结果为1
console.log(getMaxDepthByKey('tree4',treeData))结果为0
console.log(getMaxDepthByKey('tree5',treeData))结果为0
console.log(getMaxDepthByKey('tree6',treeData))结果为0
console.log(getMaxDepthByKey('tree7',treeData))结果为0
慕斯709654
浏览 1057回答 2
2回答

牧羊人nacy

经典的深度优先搜索,只有一个数据么,如果是的话,可以预处理下: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

参照楼上的修改了一下,嘻嘻vardeep=0;functiongetMaxDepthByKey(str,data){for(vari=0;i
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript