我想获得不确定树的最大深度。这棵树如下所示,我怎样才能完成它
给定一个树结构数据,获取树的最大高度。我想获得不确定树的最大深度。该树如下所示:
{
id: 1,
label: 'label1',
children: [{
id: 3,
label: 'label2',
children: [{
id: 4,
label: 'label3'
}, {
id: 5,
label: 'label4',
disabled: true,
children: [{
id: 4,
label: 'label3'
}, {
id: 5,
label: 'label4',
disabled: true
}]
}]
}
我尝试如下,但它没有按预期工作。
const maxDepth = o => {
if(!o || !o.children) return 0;
let arr = []
for(let i = 0; i< o.children.length; i++) {
arr[i] = maxDepth(o.children[i])
}
let max = Math.max(...[arr]) + 1
return max
}
given a tree-structured data, get the max height of the tree. i wanna get the max depth of a not-certain tree. the tree looks like below:
{
id: 1,
label: 'label1',
children: [{
id: 3,
label: 'label2',
children: [{
id: 4,
label: 'label3'
}, {
id: 5,
label: 'label4',
disabled: true,
children: [{
id: 4,
label: 'label3'
}, {
id: 5,
label: 'label4',
disabled: true
}]
}]
}
i tried as below, but it did not work as expected.
const maxDepth = o => {
if(!o || !o.children) return 0;
let arr = []
for(let i = 0; i< o.children.length; i++) {
arr[i] = maxDepth(o.children[i])
}
let max = Math.max(...[arr]) + 1
return max
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不相信您的数据格式 100% 正确,所以我冒昧地这样做了。话虽如此,这需要递归算法。
这几乎是我能得到的最接近的结果。 Geeks for geeks 有一篇非常好的文章和 javascript 代码来向您展示如何做到这一点,但它针对的是实际节点,而不是针对 json 之类的对象: n-ary-tree/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/depth-n-ary-tree/
I don't believe your data is formatted 100% correctly, so I took the liberty of doing so. That being said, this screams for a recursive algorithm.
This is about as close as I could get. Geeks for geeks has a pretty good artical on it and javascript code to show you how to do it, but its for actual nodes, not for json like objects: https://www.geeksforgeeks.org/depth-n-ary-tree/