[英]Javascript algorithm for a n-ary tree to find node with most children
我一直在寻找一个基本的 javascript 算法来解决这个问题,但找不到,也无法从头开始创建它。
例如,他下面的直接子节点和间接子节点数最多的节点。 所以对于下面的数据结构,我希望返回节点“12”,因为它比节点“11”有更多的死者
tree = {
"id": 1,
"children": [
{
"id": 11,
"children": [
{
"id": 111,
"children": []
},
{
"id": 112,
"children": [
{
"id": 1121,
"children": []
},
{
"id": 1122,
"children": []
}
]
}
]
},
{
"id": 12,
"children": [
{
"id": 121,
"children": []
},
{
"id": 122,
"children": [
{
"id": 8888,
"children": []
},
{
"id": 5555,
"children": [
{
"id": 6666,
"children": []
},
{
"id": 121212,
"children": []
}
]
}
]
}
]
}
]
};
很感激任何帮助,因为我很困惑。
您可以 map 每个根孩子的部门,并通过选择孩子最多的那个来减少数组。
const getC = ({ children }) => children?.reduce((sum, node) => sum + getC(node), 1) || 1, findNodeWithMostChildren = node => node.children.map((node) => [node, getC(node)]).reduce((a, b) => b[1] > a[1]? b: a) [0], tree = { id: 1, children: [{ id: 11, children: [{ id: 111, children: [] }, { id: 112, children: [{ id: 1121, children: [] }, { id: 1122, children: [] }] }] }, { id: 12, children: [{ id: 121, children: [] }, { id: 122, children: [{ id: 8888, children: [] }, { id: 5555, children: [{ id: 6666, children: [] }, { id: 121212, children: [] }] }] }] }] }; console.log(findNodeWithMostChildren(tree));
.as-console-wrapper { max-height: 100%;important: top; 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.