【问题标题】:Javascript algorithm for a n-ary tree to find node with most children用于 n 叉树的 Javascript 算法来查找具有最多子节点的节点
【发布时间】:2021-01-08 20:24:05
【问题描述】:

我一直在寻找一种基本的 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": []
                }
              ]
            }
            ]
        }
      ]
    }
  ]
};

如果我很困惑,将不胜感激。

【问题讨论】:

  • 取决于树表示。最简单 - 邻接列表中的最大值,通常 - dfs。
  • 你尝试过什么吗?
  • 图像很好,但你的树数据结构是什么样的?解决方案很大程度上取决于该结构......
  • @trincot 它是一个层次结构,我们称它为大多数员工的经理
  • 请明确指定实现的数据结构是什么。 “层次结构”仍然很模糊,并没有告诉我们您的数据结构是什么。

标签: javascript algorithm tree


【解决方案1】:

您可以为每个根子节点映射部门,并通过采用具有最多子节点的数组来减少数组。

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; }

【讨论】:

  • 这将返回节点上最多的子节点的数量,而不是节点对象(或其 id)。
  • 谢谢,这可能更符合 OP 的要求,尽管我仍然认为他们的问题不清楚(应该包括实际的数据结构而不是图片)。
  • 顺便说一句,我不希望 node 参数无效,所以没有理由使用 ?. - 只是 node.children ?? [] (或者即使没有 ?? [] 如果节点保证有空数组)就足够了
  • @NinaScholz 也为间接后代回答这个问题?
  • 你对间接后代是什么意思?
猜你喜欢
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多