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)

缺少 Node4 和 Node5。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)