python无法基于深度优先搜索的结果构建树(每个节点的高度已给定)。不确定回溯时有什么问题

2024-06-16 16:48:16 发布

您现在位置:Python中文网/ 问答频道 /正文

数据输入是具有层次结构的列表

[node0 : 0(height), node1: 1 , node2: 2, node3:2, node4:1, node5: 2]

我想要的那棵树就是这样的

     node0
     /     \ 
   node1   node4
  /    \        \
 node2  node3  node5

类似于将深度优先搜索的结果与高度一起返回到树

我的代码是

def buildFirst(root, before):
if data.__len__ == 0:
    return
toinsert = data[0]

if toinsert.height <= root.height:
    return

while toinsert.height == root.height + 1:
    root.addchildren(toinsert)
    before = toinsert
    data.pop(0)
    toinsert = data[0]

if toinsert.height > root.height + 1:
    before.addchildren(toinsert)
    data.pop(0)
    buildFirst(before, toinsert)

主要功能:

root = data[0]
 data.pop(0)
 buildFirst(root, root)

节点4和节点5缺失


Tags: datareturnifrootpopheightbeforenode1