请用python写一个完全二叉树的代码
时间: 2024-05-20 10:19:36 浏览: 89
以下是一个Python实现的完全二叉树代码:
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
class CompleteBinaryTree:
def __init__(self):
self.root = None
def insert(self, value):
if not self.root:
self.root = Node(value)
return
queue = [self.root]
while queue:
node = queue.pop(0)
if not node.left:
node.left = Node(value)
return
elif not node.right:
node.right = Node(value)
return
else:
queue.append(node.left)
queue.append(node.right)
def traverse(self):
if not self.root:
return []
result = []
queue = [self.root]
while queue:
node = queue.pop(0)
result.append(node.value)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return result
# Example usage:
tree = CompleteBinaryTree()
tree.insert(1)
tree.insert(2)
tree.insert(3)
tree.insert(4)
tree.insert(5)
tree.insert(6)
tree.insert(7)
print(tree.traverse()) # Output: [1, 2, 3, 4, 5, 6, 7]
阅读全文