Complete Binary Tree in Data Structures π³
A Complete Binary Tree (CBT) is a type of Binary Tree where:
β All levels except possibly the last are completely filled.
β All nodes are as left-aligned as possible on the last level.
π Example of a Complete Binary Tree
β Valid Complete Binary Tree:
πΉ All levels except the last are completely filled.
πΉ The last level is filled from left to right.
β Not a Complete Binary Tree:
πΉ The node 5
should have been placed before 3
's right child.
πΉ Nodes must be left-aligned on the last level.
π Properties of a Complete Binary Tree
1οΈβ£ Height of a Complete Binary Tree:
- For
n
nodes, the height h is: - Example: If
n = 6
, then
2οΈβ£ Number of Nodes:
- A complete binary tree with height
h
has at most: - Example: If height
h = 2
, max nodes =
3οΈβ£ Efficient Storage in Arrays:
- A Complete Binary Tree is ideal for Array Representation, since we can use index calculations:
π Complete Binary Tree Representation in C
πΉ Output:
π Advantages of a Complete Binary Tree
β
Efficient Memory Usage β No wasted space like in sparse trees.
β
Ideal for Heaps & Priority Queues β Used in Heap Sort & Dijkstraβs Algorithm.
β
Easier Level-Order Traversal β Can be efficiently stored in an array.
π Disadvantages
β Insertion at the Last Level β Requires maintaining a queue or array indexing.
β Not Always Height Balanced β May still need balancing for some applications.
π Where is a Complete Binary Tree Used?
β Binary Heaps β Used in heap-based sorting & scheduling algorithms.
β Priority Queues β Implemented using Min/Max Heap structures.
β Huffman Coding Trees β Used in compression algorithms.
π² Complete Binary Trees are widely used in efficient data structures & algorithms