Max Heap
Trees and HeapsA Max-Heap is a type of binary tree where the largest value is always at the top (the root), and each parent node is always greater than or equal to its child nodes.
There are some important rules that define a Max-Heap:
The tree must be a complete binary tree. This means all levels of the tree are filled except maybe the last, and nodes are filled from left to right.
Every parent node must be greater than or equal to its children.
The largest value is always at the root.
Here’s a quick example:
10
/ \
7 5
/ \ /
1 3 4How is a Max-Heap Different from a Binary Search Tree?
A Max-Heap is not the same as a BST. Here are the key differences:
1. Ordering:
In a BST, the left child must be less than the parent, and the right child must be greater than the parent.
In a Max-Heap, the only rule is that the parent is greater than or equal to its children. It doesn’t matter whether the child is on the left or right.
2. Structure:
A BST can be unbalanced and irregular depending on how items are inserted.
A Max-Heap is always a complete binary tree. They are very compact and always filled left to right.
3. Use Cases:
BSTs are used for fast lookups, insertions, and deletions.
Max-Heaps are used when we constantly need access to the largest item quickly (like in priority queues).
Why Use a Max-Heap?
Max-Heaps are great for situations where you need to:
Quickly find or remove the largest element
Keep elements partially sorted
Implement priority queues, heap sort, or scheduling algorithms
They are fast. Insertion and removal take O(log n) time and getting the maximum value takes O(1).
Max Heap Structure
Unlike BSTs or AVLs that are made with nodes and pointers, a Max-Heap is stored using just a simple array (or a vector). We don’t need to create any structs or pointers to manage left and right children.
This works because Max-Heaps are always complete binary trees. That means:
Every level of the tree is completely filled, except maybe the last one.
The last level fills from left to right.
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 42 more lessons in Data Structures & Algorithms.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- Mock exams marked by hand, with feedback
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel anytime.