👀 Peek in Heap Tree (Min/Max Heap)

Follow Me

Definition:
The peek() operation in a Heap Tree returns the root element:

  • In a Max Heap, it returns the maximum element.

  • In a Min Heap, it returns the minimum element.

⚠️ It does not remove the element — just views it.

📌 Time Complexity

  • O(1) — Since the root is always at index 0 (in array representation).

📊 Basic Diagram (Max Heap Example)

60 / \ 30 50 / \ / 10 20 40


🔍 peek() → returns 60 (root of Max Heap)


🧠 Python Code for peek() in Max Heap

class MaxHeap: def __init__(self): self.heap = [] def insert(self, value): self.heap.append(value) self._heapify_up(len(self.heap) - 1) def peek(self): if not self.heap: return None return self.heap[0] def _heapify_up(self, index): parent = (index - 1) // 2 if index > 0 and self.heap[index] > self.heap[parent]: self.heap[index], self.heap[parent] = self.heap[parent], self.heap[index] self._heapify_up(parent) # Example usage h = MaxHeap() for val in [60, 30, 50, 10, 20, 40]: h.insert(val) print("Top Element (Peek):", h.peek()) # Output: 60


📝 Summary of peek() Operation

FeatureDescription
Purpose    View the root element
Modifies Heap?    ❌ No
Time Complexity    O(1)
Used in    Priority Queue, Scheduling

No comments:

Post a Comment

Recursion in DSA using Python

Follow me If you want to understand with  Graphical Representation   click on it. You can find the explanatory video at the bottom of this p...