Data Structure and AlgorithmsUnit 610 min read
Trees: Types, Traversals, BSTs, AVL Trees & Applications
Unit 6 of Data Structure and Algorithms covers tree structures—hierarchical data models with nodes and edges—including binary trees, binary search trees (BSTs), AVL trees, tree traversals (DFS/BFS), and real-world applications like file systems, organizational charts, and decision trees in machine learning.
TAKEAWAYS:
- Trees represent hierarchical relationships (parent-child) and are used in databases, compilers, and AI.
- Binary trees have at most two children per node; BSTs enforce left ≤ root ≤ right for efficient searching.
- AVL trees self-balance to maintain operations via rotations after insertions/deletions.
- Traversals (pre-order, in-order, post-order, level-order) visit nodes in different sequences for distinct tasks.
- Heap (priority queue) trees support efficient min/max extraction via complete binary tree properties.
- Real-world uses include Daraz’s product category trees, WhatsApp’s message thread hierarchy, and Nepal’s NTC’s network routing tables.
1. Introduction to Trees
A tree is a non-linear, hierarchical data structure with:
- Nodes: Data elements (e.g.,
value,left/right child pointers). - Edges: Links between nodes (parent-child relationships).
- Root: The topmost node (no parent).
- Leaf: A node with no children.
- Subtree: A tree derived from a node (its children + descendants).
Key Properties:
- No cycles (acyclic).
- nodes have edges.
- Degree: Number of children of a node.
- Height: Longest path from root to leaf.
Example: File system directories (folders as nodes, files as leaves).
2. Types of Trees
A. Binary Trees
- Each node has at most 2 children (left/right).
- Types:
- Full Binary Tree: Every node has 0 or 2 children.
- Complete Binary Tree: All levels filled except possibly the last, which is left-filled.
- Perfect Binary Tree: All levels completely filled (height = ).
Example: WhatsApp’s message tree (threads as binary branches for replies).
B. Binary Search Trees (BST)
- Property: For any node:
- Left subtree ≤ node < right subtree.
- Operations:
- Search: (height).
- Insertion/Deletion: .
- Traversals: In-order yields sorted order.
graph TD
A["10"] --> B["5"]
A --> C["15"]
B --> D["2"]
B --> E["7"]
C --> F["12"]
C --> G["20"]Worked Example: Insert 8 into the BST above.
Steps:
- Start at root (10): 8 < 10 → go left.
- At 5: 8 > 5 → go right.
- Insert 8 as right child of 5. State after insertion:
graph TD
A["10"] --> B["5"]
A --> C["15"]
B --> D["2"]
B --> E["8"]
C --> F["12"]
C --> G["20"]Code (C):
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
Node* insert(Node* root, int data) {
if (!root) return newNode(data);
if (data < root->data) root->left = insert(root->left, data);
else root->right = insert(root->right, data);
return root;
}
Trace:
| Step | Node Visited | Action |
|---|---|---|
| 1 | 10 | Go left (8 < 10) |
| 2 | 5 | Go right (8 > 5) |
| 3 | NULL | Insert 8 as right of 5 |
3. Tree Traversals
Traversals visit nodes in specific orders. Four types:
| Traversal | Order | Use Case |
|---|---|---|
| Pre-order | Root → Left → Right | Copy a tree, prefix notation |
| In-order | Left → Root → Right | BST → sorted list |
| Post-order | Left → Right → Root | Delete a tree, postfix notation |
| Level-order | Level by level | Breadth-first search (BFS) |
Example: In-order traversal of the BST above yields [2, 5, 7, 8, 10, 12, 15, 20].
Code (Level-order):
void levelOrder(Node* root) {
Queue q;
q.enqueue(root);
while (!q.isEmpty()) {
Node* temp = q.dequeue();
printf("%d ", temp->data);
if (temp->left) q.enqueue(temp->left);
if (temp->right) q.enqueue(temp->right);
}
}
Trace:
| Queue State | Node Processed | Output |
|---|---|---|
| [10] | 10 | 10 |
| [5, 15] | 5 | 10 5 |
| [15, 2, 7] | 15 | 10 5 15 |
| [2, 7, 12, 20] | 2 | 10 5 15 2 |
| ... | ... | ... |
4. AVL Trees (Self-Balancing BSTs)
Problem: BSTs degrade to if unbalanced (e.g., sorted input). Solution: AVL trees enforce balance factor (BF):
- .
- Constraint: for all nodes.
Rotations (to rebalance):
- Left Rotation: Right-heavy subtree.
- Right Rotation: Left-heavy subtree.
- Left-Right/Right-Left: Double rotations for zig-zag imbalances.
Example: Insert 1, 2, 3 into an AVL tree.
Steps:
- Insert 1 → root.
- Insert 2 → right child of 1 (BF = 0).
- Insert 3 → right child of 2 (BF = 1 for 2, 0 for 1). Imbalance detected at 1 (BF = -2) → Left Rotation at 1. Final Tree:
Code (AVL Insertion):
int height(Node* node) { ... }
int getBF(Node* node) { ... }
Node* rightRotate(Node* y) { ... }
Node* leftRotate(Node* x) { ... }
Node* insert(Node* root, int data) {
if (!root) return newNode(data);
if (data < root->data) root->left = insert(root->left, data);
else root->right = insert(root->right, data);
root->height = 1 + max(height(root->left), height(root->right));
int BF = getBF(root);
// Left Left Case
if (BF > 1 && data < root->left->data)
return rightRotate(root);
// Other cases...
return root;
}
5. Applications of Trees
| Tree Type | Application | Example (Nepal/Global) |
|---|---|---|
| Binary Tree | Expression evaluation (e.g., (a+b)*c) |
eSewa’s bill parsing (tax calculations) |
| BST | Database indexing, autocompletion | Google Search’s keyword ranking |
| AVL Tree | Real-time systems (low latency) | Ncell’s call routing tables |
| Heap (Priority Q) | Dijkstra’s algorithm, task scheduling | Pathao’s driver assignment |
| Trie | Spell checkers, IP routing | NTC’s network prefix tables |
| Decision Tree | Machine learning (classification) | Nepal Rastra Bank’s loan approval |
Real-World Example 1: Daraz’s Product Categories
- Structure: Multi-level tree (Electronics → Mobiles → Samsung → Galaxy S23).
- Why Trees?:
- Fast lookup (BST) for product searches.
- Hierarchical navigation (parent-child relationships).
- Operation: When you click "Mobiles," Daraz traverses the tree to fetch subcategories.
Real-World Example 2: WhatsApp Message Threads
- Structure: Binary tree for replies (root = original message, children = replies).
- Why Trees?:
- Pre-order traversal flattens threads for reading.
- AVL-like balancing ensures quick reply insertion.
Real-World Example 3: NTC’s Network Routing
- Structure: Trie or tree for IP address prefixes (e.g.,
192.168.1.*). - Why Trees?:
- Longest prefix match (e.g.,
192.168.1.100vs192.168.*). - Efficient routing tables (AVL for dynamic updates).
- Longest prefix match (e.g.,
6. Comparison: Trees vs. Other Structures
| Feature | Array | Linked List | BST | Hash Table |
|---|---|---|---|---|
| Access Time | (random) | (avg ) | (avg) | |
| Search Time | (linear) | |||
| Insertion/Deletion | (shifting) | (avg) | ||
| Ordering | Fixed | None | Sorted (BST) | Unordered |
| Use Case | Static data | Dynamic data | Sorted data, ranges | Fast lookups |
When to Use Trees?
- Need hierarchical data (e.g., org charts, file systems).
- Frequent search/insert/delete with ordering (BST/AVL).
- Priority-based operations (heaps).
7. Exam Tip
What Examiners Look For:
- Definitions: Clearly define tree, BST, AVL tree, and traversals.
- Visuals: Draw trees after each operation (insertion/deletion/rotation).
- Example: Show the BST before and after inserting
8(as above).
- Example: Show the BST before and after inserting
- Time Complexity: State for BST operations; for AVL.
- Code + Trace: Write pseudocode for traversals/rotations and trace with a table.
- Real-World Links: Relate to Nepali apps (eSewa, Daraz, NTC) or global tech (Google, WhatsApp).
- Common Pitfalls:
- Forgetting to update heights in AVL trees.
- Incorrect rotation cases (e.g., confusing left-right with right-left).
- Off-by-one errors in traversal order.
Sample Exam Questions:
- "Insert
5, 3, 7, 2into a BST and show the tree after each step." - "Explain how AVL trees maintain balance with an example."
- "Compare the time complexity of searching in a BST vs. a hash table."
- "How would you implement a spell checker using a trie?"
Marks Distribution (Typical):
- 3 marks: Definitions/diagrams.
- 4 marks: Step-by-step operations (insertion/traversal).
- 3 marks: Code + trace.
- 2 marks: Real-world application.
Tree representation of folders/files (Image: Peter Flass, CC BY-SA 4.0, via Wikimedia Commons)
Based on the PU BE Computer (PU) syllabus for Data Structure and Algorithms (CMP160), unit 6.
Discussion
Loading…