Binary tree BFS traversal - AttributeError: 'list' object has no attribute 'value'
Binary tree BFS traversal - AttributeError: 'list' object has no attribute 'value'
class BinaryTreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def level_order_traversal(root):
q = []
result = []
if not root:
return result
q.append(root)
while q:
temp_q = []
res_q = []
node = q.pop(0)
res_q.append(node.value)
if node.left:
temp_q.append(node.left)
if node.right:
temp_q.append(node.right)
q = temp_q
result.append(res_q)
return result
if __name__ == "__main__":
result = level_order_traversal([0, 1, None, None, 2, 4, None, None, 3])
print(result)
代码挑战站点通常会将 JSON 输入转换为给定 class 的实例——在本例中为 BinaryTreeNode
和相同的嵌套实例。
一旦您决定在代码挑战框架之外测试您的代码,您就必须自己做好准备。如果您希望它使用列表作为输入,请将此辅助函数添加到您的工具集中:
def to_binary_tree(items):
if not items:
return None
it = iter(items)
root = BinaryTreeNode(next(it))
q = [root]
for node in q:
val = next(it, None)
if val is not None:
node.left = BinaryTreeNode(val)
q.append(node.left)
val = next(it, None)
if val is not None:
node.right = BinaryTreeNode(val)
q.append(node.right)
return root
现在您可以:
if __name__ == "__main__":
result = level_order_traversal(to_binary_tree([0, 1, None, None, 2, 4, None, None, 3]))
print(result)
class BinaryTreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def level_order_traversal(root):
q = []
result = []
if not root:
return result
q.append(root)
while q:
temp_q = []
res_q = []
node = q.pop(0)
res_q.append(node.value)
if node.left:
temp_q.append(node.left)
if node.right:
temp_q.append(node.right)
q = temp_q
result.append(res_q)
return result
if __name__ == "__main__":
result = level_order_traversal([0, 1, None, None, 2, 4, None, None, 3])
print(result)
代码挑战站点通常会将 JSON 输入转换为给定 class 的实例——在本例中为 BinaryTreeNode
和相同的嵌套实例。
一旦您决定在代码挑战框架之外测试您的代码,您就必须自己做好准备。如果您希望它使用列表作为输入,请将此辅助函数添加到您的工具集中:
def to_binary_tree(items):
if not items:
return None
it = iter(items)
root = BinaryTreeNode(next(it))
q = [root]
for node in q:
val = next(it, None)
if val is not None:
node.left = BinaryTreeNode(val)
q.append(node.left)
val = next(it, None)
if val is not None:
node.right = BinaryTreeNode(val)
q.append(node.right)
return root
现在您可以:
if __name__ == "__main__":
result = level_order_traversal(to_binary_tree([0, 1, None, None, 2, 4, None, None, 3]))
print(result)