The UCX DSA package provides three heap-based data structures:
Heap - A max heap implementation
MinHeap - A min heap implementation
PriorityQueue - A priority queue built on top of MinHeap
Heaps are complete binary trees that maintain the heap property: in a max heap, each parent node is greater than or equal to its children; in a min heap, each parent is less than or equal to its children.
The heap is stored as an array with parent-child relationships:
heap = Heap.from_list([10, 20, 30, 40, 50])# Get child indicesleft_idx = heap.left_index(0) # Left child of rootright_idx = heap.right_index(0) # Right child of root# Get parent indexparent_idx = heap.parent_index(2) # Parent of node at index 2# Check for childrenhas_left = heap.has_left(0) # Returns True if left child existshas_right = heap.has_right(0) # Returns True if right child exists
heap = Heap.from_list([5, 3, 8, 1, 9])# Check if emptyif heap.is_empty(): print("Heap is empty")# Get countcount = heap.count()print(f"Heap has {count} elements")# Or use len()print(len(heap)) # Same as count()# View raw array representationarray = heap.raw_view()print(array) # [9, 5, 8, 1, 3]# Get sorted list (non-destructive)sorted_list = heap.to_sorted_list()print(sorted_list) # [9, 8, 5, 3, 1] (descending)
Visualize heaps as binary trees using the HeapDraw class:
from dsa.heap import Heapfrom dsa.draw import HeapDraw# Create and populate a heapheap = Heap.from_list([50, 30, 70, 20, 40, 60, 80])# Visualize the heaphd = HeapDraw(heap)hd.draw() # Display the heap as a tree# Save to filehd.save("my_heap.png")# Adjust figure sizehd.set_figsize((8, 6))hd.draw()
The visualization converts the array-based heap into a tree structure for better understanding of the heap property.