如何从给定的父子列表创建树,但是不能在其父节点之前创建子节点?

问题描述 投票:1回答:1

列表包含父母和孩子。根节点的父节点为-1。我必须从这里创建一棵树,但是在其父节点之前不能创建任何子节点。

父母的子女名单

3 7
3 6 
2 5
-1 1
2 4
1 2
1 3
algorithm tree breadth-first-search dfs
1个回答
0
投票

以下算法将起作用:

  1. MapInteger初始化为List/Array[Integer]。这里,key代表ParentList/Array[Integer]代表Childrens
  2. 迭代所提到的parent child list。对于每个条目,填充在步骤1中创建的Map。即,对于问题中提到的示例,Map如下所示: -1 -> [1] 1 -> [2, 3] 2 -> [4, 5] 3 -> [6, 7]
  3. 一旦准备好Map,请按键对Map进行排序。
  4. 对于Key, Value中的每个Map,为父级创建节点,然后为其子级创建节点。对于其余的Key, Value对,请遵循此规则。

这将确保总是在Parent之前准备好Child

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.