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
| Feature | Description |
|---|---|
| Purpose | View the root element |
| Modifies Heap? | ❌ No |
| Time Complexity | O(1) |
| Used in | Priority Queue, Scheduling |
No comments:
Post a Comment