可以通过以下步骤实现:
class Node {
constructor(value) {
this.value = value;
this.children = [];
}
}
function findNodeWithMostChildren(root) {
let maxChildrenCount = 0;
let nodeWithMostChildren = null;
function dfs(node) {
if (node.children.length > maxChildrenCount) {
maxChildrenCount = node.children.length;
nodeWithMostChildren = node;
}
for (let child of node.children) {
dfs(child);
}
}
dfs(root);
return nodeWithMostChildren;
}
// 创建一个示例n叉树
const root = new Node(1);
const node2 = new Node(2);
const node3 = new Node(3);
const node4 = new Node(4);
const node5 = new Node(5);
const node6 = new Node(6);
const node7 = new Node(7);
const node8 = new Node(8);
const node9 = new Node(9);
root.children.push(node2, node3, node4);
node2.children.push(node5, node6);
node3.children.push(node7);
node4.children.push(node8, node9);
// 寻找子节点最多的节点
const nodeWithMostChildren = findNodeWithMostChildren(root);
console.log(nodeWithMostChildren.value); // 输出1,根节点的子节点最多
这个算法的时间复杂度是O(n),其中n是树中节点的数量。
领取专属 10元无门槛券
手把手带您无忧上云