微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python无法根据深度优先搜索的结果给定每个节点的高度构建树不知道回溯时有什么问题

如何解决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 举报,一经查实,本站将立刻删除。