【发布时间】:2020-07-13 10:13:58
【问题描述】:
我已经实现了一个看起来像这样的树:
1
2 3 4
5 6 7 8
我想以广度打印。这是我的代码:
class Node:
def __init__(self):
self.data = None
self.children = []
class Tree:
def __init__(self):
self.root = Node()
def build(self):
self.root.data = 1
self.root.children.append(Node())
self.root.children.append(Node())
self.root.children.append(Node())
self.root.children[0].data = 2
self.root.children[1].data = 3
self.root.children[2].data = 4
self.root.children[0].children.append(Node())
self.root.children[0].children.append(Node())
self.root.children[2].children.append(Node())
self.root.children[2].children.append(Node())
self.root.children[0].children[0].data = 5
self.root.children[0].children[1].data = 6
self.root.children[2].children[0].data = 7
self.root.children[2].children[1].data = 8
return
def traverseBF(self, node):
li = []
trav = []
li.append(node)
while len(li) != 0:
for x in li:
trav.append(x.data)
for z in x.children:
li.append(z)
# map(lambda z: li.append(z), x.children)
li.remove(x)
print(trav)
t = Tree()
t.build()
t.traverseBF(t.root)
输出为:[1, 3, 2, 5, 4, 7, 6, 8]
我的问题是:
- 为什么 3 在 2 之前被插入到 trav[] 中,即使在 root.children 中的顺序是 [2,3,4]
- 为什么注释掉的 map 函数给出的结果与上面的 for 循环不同?
【问题讨论】:
-
在循环中使用 append 或使用带有副作用的 map 都是扩展列表的非常不合 Python 的方式。请改用
list.extend()方法。
标签: python list tree traversal