【发布时间】:2019-03-09 15:09:16
【问题描述】:
鉴于这棵树:
7
5 9
_ 6 8 _
_ _ _ _
我希望输出是:
[[Node(7)], [Node(5), Node(9)], [None, Node(6), Node(8), None], [None, None, None, None]]
因此,重要的是包含“无”并且输出是列表中的列表。
我尝试了很多东西,但这就是我现在所处的位置:
class Node(object):
def __init__(self, key, value=None):
self.key = key
self.value = value
self.parent = None
self.left_child = None
self.right_child = None
self.height = 0
def breadth_first_traversal(self):
self.height = 1
to_do = [self.root]
if (self.root == None):
return to_do
output = []
current_height = self.height
output.append([str(node) for node in to_do])
while (to_do):
done = []
current = to_do.pop(0)
if (current.height > current_height):
current_height += 1
if (current.left_child):
current.left_child.height = current_height + 1
to_do.append(current.left_child)
done.append(current.left_child)
elif (not current.left_child):
done.append(None)
if (current.right_child):
current.right_child.height = current_height + 1
to_do.append(current.right_child)
done.append(current.right_child)
elif (not current.right_child):
done.append(None)
output.append([str(node) for node in done])
print(output)
return output
现在的输出是:
[['7'], ['5', '9'], ['None', '6'], ['8', 'None'], ['None', 'None'], ['None', 'None']]
我理解它为什么要制作包含 2 个元素的列表,因为这就是我所说的它现在应该做的事情。我只是不知道如何考虑级别。
【问题讨论】:
标签: python binary-search-tree breadth-first-search