Print the heap by tree traversal (Levelorder/Preorder, postorder, inorder traversal) anyone would be OK.
时间: 2023-12-26 14:48:51 浏览: 30
Sure! Here's an example of how to print a heap (assuming it's a binary heap) by level-order traversal using Python:
```python
def print_heap(heap):
"""
Prints the elements of a binary heap by level-order traversal.
"""
if not heap:
return
level = 0
nodes_in_level = 1
index = 0
while index < len(heap):
print("Level", level, end=": ")
for i in range(nodes_in_level):
if index >= len(heap):
break
print(heap[index], end=" ")
index += 1
print()
level += 1
nodes_in_level *= 2
```
This function works by keeping track of the current level and the number of nodes in that level. It then iterates through the heap, printing out the elements in each level until it reaches the end of the heap.
You can also print a heap by preorder, postorder, or inorder traversal by modifying the traversal algorithm accordingly. For example, here's how you could print a heap by preorder traversal:
```python
def preorder_print(heap, index=0):
"""
Prints the elements of a binary heap by preorder traversal.
"""
if index >= len(heap):
return
print(heap[index], end=" ")
preorder_print(heap, 2*index+1)
preorder_print(heap, 2*index+2)
```
This function recursively prints the current node, then traverses the left and right subtrees in preorder fashion.