3. Explain Heap, Bottom-up Heap and Top-down heap with example.
Answer:
A heap is a binary tree that satisfies two main conditions:
- Shape Property: The tree is complete—all levels are full, except possibly the last, which is filled from left to right.
- Heap Property (Parental Dominance): The key in each node is greater than or equal to its children.
(Automatically true for leaves.)

Properties of Heaps
- Exactly one complete binary tree exists for n nodes.
- Root always contains the largest element.
- Any subtree (node and its descendants) is also a heap.
- A heap can be stored in an array H[1..n] with:
- Parents in first n/2 positions.
- Children of node at position i in 2i and 2i+1.
- Parent of node at i is at position i/2.
Heap Property in Array Form:
H[i] ≥ max(H[2i], H[2i+1]) for all i = 1 to n/2

Bottom-Up Heap Construction
- Place the list of n keys in level-order into a complete binary tree.
- Start from the last parent node and “heapify”:
- Compare parent with children.
- Swap with larger child if needed.
- Repeat until parental dominance is satisfied.
Bottom-up heap construction for input: 2, 9, 7, 6, 5, 8.

Worst-Case Efficiency:
- Total comparisons in worst case ≈ 2(n − log₂(n + 1))
- Hence, time complexity: O(n)
Top-Down Heap Construction (Insertion Method)
- Insert key K as the last leaf.
- “Sift up” by comparing with parent:
- If parent ≥ K, stop.
- Else, swap and continue up.
Inserting 10 into the heap—sift-up process.

Time Complexity: O(log n) (height of the heap)
Deleting the Maximum (Root) Key
- Swap root with last key K.
- Reduce heap size by 1.
- “Sift down” K by swapping with the larger child until heap property is restored.
Deleting the root’s key and restoring heap structure.

Time Complexity: O(log n)