Binary Tree Representations
Binary Tree Representations
There are two main ways to represent a binary tree:
Method | Description |
---|---|
1. Array Representation | Tree is stored as an array (indexing rules are used). |
2. Linked Representation | Each node has pointers to its left and right child. |
1. 📦 Array Representation of Binary Tree
In this method:
-
The tree is stored in a one-dimensional array.
-
Each node's position depends on the index of its parent.
✅ Index Rules:
If a node is stored at index i
:
-
Left Child → stored at index 2i + 1
-
Right Child → stored at index 2i + 2
-
Parent → stored at index (i - 1)/2 (integer division)
✏️ Example
Let's consider this binary tree:
Store in array (level order):
Index | 0 | 1 | 2 | 3 | 4 | 5 |
---|---|---|---|---|---|---|
Value | A | B | C | D | E | F |
-
A
at index 0 -
B
at index 1 → left child of A -
C
at index 2 → right child of A -
D
at index 3 → left child of B -
E
at index 4 → right child of B -
F
at index 5 → left child of C
✅ Advantages of Array Representation
-
Easy and fast access (just index calculations).
-
Best suited for complete binary trees (like heaps).
❌ Disadvantages
-
Wastes space for non-complete trees (many NULLs).
-
Difficult to manage dynamic insertion/deletion.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
A B C D E F G H
C Program Array Representation of Tree
2. 🔗 Linked Representation of Binary Tree
Here:
-
Each node is a structure (or object) with 3 parts:
-
Data
-
Pointer to Left Child
-
Pointer to Right Child
-
✏️ Structure
In C language:
Each node is dynamically created and linked.
✅ Advantages of Linked Representation
-
Memory efficient for sparse trees.
-
Easy to perform dynamic insertion and deletion.
❌ Disadvantages
-
Slower random access (must traverse pointers).
-
Requires more memory (extra space for pointers).
Comments
Post a Comment