给定存储在父数组中的n-ary树,子节点存储在指向数组的指针数组中,其中第一个值是子节点数:
(childArray [2] [0]显示节点2有2个子节点,childArray [2] [1]显示它的第一个子节点是5,等等。)
parentArray = {3, 0, 3, -1, 3, 2, 2};
childArray = {{1, 1}, {0}, {2, 5, 6}, {3, 0, 2, 4}, {0}, {0}, {0}};
生成一个如下所示的树:
3
/|\
0 2 4
| |\
1 5 6
使用队列,我如何按级别输出树级别:
等级1:3
等级2:0,2,4
等级3:1,5,6
1级和2级很容易,因为1级只是它的根,2级只是它的孩子,但在那之后我无法弄清楚如何让它来接收孩子的孩子。
答案 0 :(得分:0)
这样做的一种方法是使用queue数据结构。
从一些队列 q 开始,并放在父级为-1的(唯一)项的索引中。现在,在每一步,直到 q 为空,
例如,以下是您案例的第一步:
几乎按照定义,由于 q 从前面弹出并添加到后面,因此将逐级处理节点。
复杂度在节点数量上是线性的。
答案 1 :(得分:0)
您必须在树上执行BFS(广度优先搜索),同时保持推入下一级别的节点数。概要:
q.push(root); nodesInCurrentLevel = 1; nodesInNextLevel = 0; currentLevelIndex = 1;
while q is not empty do:
u = q.pop()
print currentLevelIndex and u
decrement nodesInCurrentLevel
for every child v of u do:
increment nodesInNextLevel
q.push(v)
if nodesInCurrentLevel is 0 do:
nodesInCurrentLevel = nodesInNextLevel
nodesInNextLevel = 0
increment currentLevelIndex
当然,这会将输出打印为Level 2:0 Level 2:2等。您可以将当前级别节点存储在循环内的临时列表中并根据需要进行打印。