algorithm - 如何用树中的所有子节点替换节点

标签 algorithm tree graph-algorithm

我想知道如何用它的 child 替换非二叉树的节点。例如,我将从这样的结构开始:

        a
     / / \ \
    b  c  d e
   /\  /    /\\
  f  g h    i jk

如果我将节点 e 替换为它的子节点,则以这个结束

          a
     / / \ \ \ \
    b  c  d i j k
   /\  / 
  f  g h    

在 JSON 中,初始结构如下所示:

{
  "id": "a",
  "children": [
    {
      "id": "b",
      "children": [
        {
          "id": "f",
          "children": []
        },
        {
          "id": "g",
          "children": []
        }
      ]
    },
    {
      "id": "c",
      "children": [
        {
          "id": "h",
          "children": []
        }
      ]
    },
    {
      "id": "d",
      "children": []
    },
    {
      "id": "e",
      "children": [
        {
          "id": "i",
          "children": []
        },
        {
          "id": "j",
          "children": []
        },
        {
          "id": "k",
          "children": []
        }
      ]
    }
  ]
}

最佳答案

如果稍微更改一下 JSON 结构,您的问题就会变得容易得多。 对于每个节点,存储每个节点的父节点及其直接子节点。

新的 JSON 结构

[
  {"id": "a", "parent": null, "children" : ["b", "c", "d", "e"] },
  {"id": "b", "parent": "a",  "children" : ["f", "g"]},
  {"id": "c", "parent": "a",  "children" : ["h"]},
  {"id": "d", "parent": "a",  "children" : []},
  {"id": "e", "parent": "a",  "children" : ["i", "j", "k"]}
]

算法

假设您的目标节点是e

现在您需要做的就是将 e 的直接子级的父级更改为 a,因为 a 的父级>e。然后删除e

这将保留 e 的子树结构。如果您不希望这样做,那么您必须递归地将 a 作为父级分配给 e 的所有子级,而不仅仅是直接的子级。

关于algorithm - 如何用树中的所有子节点替换节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56979142/

相关文章:

java - 等于整数

java - 完全二叉树和完美二叉树定义

algorithm - 如何找到具有价约束的二部图的最大子图?

algorithm - 确定算法中的步骤数

python - 如何在 Tree 方法中正确放置 return False 语句?

python - 双向 A* 未找到最短路径

algorithm - 找到从一个到另一个的所有可能方法的时间复杂度是多少?

c++ - 排序算法和对象指针的问题

algorithm - 找到一系列间隔的最有效分组

algorithm - 我应该使用什么编程语言、算法来进行字典翻译?