写一段代码实现完全二叉树
时间: 2023-10-31 12:12:59 浏览: 83
Python实现完全二叉树
Sure, here is an example code to implement a complete binary tree in Python:
```
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class CompleteBinaryTree:
def __init__(self):
self.root = None
def insert(self, val):
new_node = Node(val)
if self.root is None:
self.root = new_node
return
queue = [self.root]
while queue:
curr = queue.pop(0)
if curr.left is None:
curr.left = new_node
break
elif curr.right is None:
curr.right = new_node
break
queue.append(curr.left)
queue.append(curr.right)
```
This code defines a `Node` class for each node in the tree and a `CompleteBinaryTree` class to represent the entire tree. The `insert` method adds a new node to the tree by traversing the tree in a breadth-first manner and finding the first empty spot for the new node. This ensures that the tree remains complete.
阅读全文