Top Banner Ad

ACS201 — Unit 5: Trees and Graphs (Concept Level)

Table of Contents (23 sections)

ACS201 · Essentials of Data Structures · Unit 5

Trees and Graphs (Concept Level)

Unit Scope & Exam Weightage: This unit moves from linear structures to hierarchical and networked structures: Trees and Graphs (Concept Level), Binary tree — terminology (root, leaf, height, level), properties, Binary Search Tree — insert, search, inorder/preorder traversal trace, Graph — vertex, edge, directed/undirected, adjacency list representation, insertion and BFS and DFS — trace on a small graph (5– 6 nodes). The solutions file supplies only generic 2026-27 model-paper templates for ACS201, not real past-paper questions, so every worked question here is explicitly labelled predicted and is derived from these exact syllabus items and their assignment traces.


Front Page: Importance-Wise Topic Roadmap (Predicted from Syllabus)

Priority Topic (Exact Syllabus) PYQs Asked Marks Weightage Tag
1 Binary Search Tree — insert + search 0 real PYQs predicted 7m Predicted Program
2 inorder/preorder traversal trace 0 real PYQs predicted 7m Predicted Trace
3 BFS and DFS — trace on a small graph (5– 6 nodes) 0 real PYQs predicted 7m Predicted Trace
4 adjacency list representation + insertion 0 real PYQs predicted 7m Predicted Program
5 Binary tree — terminology (root, leaf, height, level) + properties 0 real PYQs predicted 2m + 5m Predicted Theory
6 Graph — vertex, edge, directed/undirected 0 real PYQs predicted 2m Predicted Theory
7 Trees and Graphs (Concept Level) Real connect: File system = tree integrated in #1–#4 — Real Connect
8 BST in database indexing, Google Maps = weighted graph, Social network = graph, Decision Tree in ML = binary tree integrated in #1, #4 — Real Connect
9 Suggested Assignment / Practice Problems (Unit-wise) but not limited to No Tutorial hour in ACS201 0 real PYQs 2–3 per unit Practice Checklist

2-Hour Last-Night Survival Checklist:

  1. BST insert rule: compare with the root; go left if smaller, right if larger. State the duplicate policy before coding (here duplicates go right). Inserting 50,30,70,20,40 gives root 50, left child 30 with children 20 and 40, right child 70.
  2. Traversal order: inorder is left → root → right and gives a sorted list for a BST; preorder is root → left → right. For the tree above: inorder 20,30,40,50,70; preorder 50,30,20,40,70.
  3. Tree properties: an n-node tree has n-1 edges; level i holds at most 2^i nodes; with root at level 0 and height measured in edges, a perfect tree of height h has 2^(h+1)-1 nodes.
  4. Graph list rule: for an undirected edge A-B, write B in adj[A] and A in adj[B]; for a directed edge A→B, write B only in adj[A]. Appending to a Python list is O(1).
  5. BFS vs DFS: BFS uses a FIFO queue and visits level by level; DFS uses a LIFO stack/recursion and follows one branch to the end. On edges A-B, A-C, B-D, C-E with alphabetical neighbours, BFS from A is A,B,C,D,E and DFS is A,B,D,C,E.

1. Trees and Graphs (Concept Level)

Tree: a connected, acyclic structure of nodes with exactly one root. Every node except the root has one parent; a node may have zero or more children. Graph: a set of vertices connected by edges; no unique root exists and cycles are allowed.

Feature Tree Graph
Shape Hierarchical Network
Root Exactly one None
Parent One per non-root node Any number / none
Cycles Not allowed Allowed
Edges for n nodes Exactly n-1 Any number up to n(n-1)/2 (undirected)
Real connect File system, decision tree Social network, Google Maps
%%{init: {'theme': 'base', 'look': 'handDrawn', 'themeVariables': {'fontFamily': "'Nunito', sans-serif", 'fontSize': '17px', 'primaryColor': '#EFEAD6', 'primaryBorderColor': '#0F766E', 'lineColor': '#23211C'}}}%%
flowchart TD
    subgraph T[Tree]
        TR[Root] --> TA[Child A]
        TR --> TB[Child B]
        TA --> TL[Leaf]
    end
    subgraph G[Graph]
        GA --- GB
        GA --- GC
        GB --- GD
        GC --- GD
    end

Why this unit matters: a file system is a tree because every folder except the root has one parent; a social network is a graph because a person may have many friends and friendship cycles are normal. A decision tree in ML is a binary tree because each internal node asks a yes/no question.

Examiner Tip: If asked “tree vs graph”, answer with three contrasts only: one root vs no root, no cycles vs cycles allowed, and n-1 edges vs variable edges. Add one real example per side. This fits a 2-mark or 5-mark answer without padding.


2. Binary Tree — Terminology and Properties

Binary tree: a tree in which each node has at most two children, named left and right. The root is the top node with no parent; a leaf has no children; the level of a node is its distance in edges from the root (root is level 0); the height is the number of edges on the longest root-to-leaf path.

Term Meaning Example in 50/30,70/20,40 tree
Root Only node with no parent 50
Parent Node directly above 30 is parent of 20 and 40
Child Node directly below 20 and 40 are children of 30
Leaf Node with no children 20, 40, 70
Level Edge distance from root 50→level 0; 30,70→level 1; 20,40→level 2
Height Longest root-to-leaf edge count 2 edges (50→30→20)
Internal node Node with at least one child 50, 30
nodes at level i≤2i,total nodes up to height h≤2h+1−1,minimum height=⌈log⁡2(n+1)⌉−1\text{nodes at level } i \le 2^i,\qquad \text{total nodes up to height } h \le 2^{h+1}-1,\qquad \text{minimum height} = \lceil \log_2(n+1)\rceil - 1

Worked property check: for the BST with nodes 50,30,70,20,40, n = 5, so edges = n-1 = 4. Height is 2; a perfect tree of height 2 would hold 2^3-1 = 7 nodes, so this tree is not perfect. The minimum height for 5 nodes is ceil(log2 6)-1 = 3-1 = 2, which this tree achieves.

Full vs complete (only the useful exam distinction): a full binary tree has every node with 0 or 2 children; a complete binary tree fills every level except possibly the last, and the last level is filled left to right. The example BST is full but not complete (level 2 has children only under 30, not under 70).

Examiner Tip: State the height convention before using a formula. This note uses root level 0 and height in edges; if an examiner counts levels instead, height would be h+1. Writing the convention avoids losing a mark on a formula question.


Binary Search Tree (BST): a binary tree in which every node in the left subtree has a key smaller than the node, and every node in the right subtree has a key larger than the node. This ordering makes search follow one path instead of scanning the whole tree.

3.1 Insertion algorithm

  1. Start at the root. If the tree is empty, the new key becomes the root.
  2. If key < current->data, go to the left child; if key > current->data, go to the right child.
  3. Repeat until the required child is NULL.
  4. Allocate a new node and attach it there. If duplicates are allowed, define a fixed side (this note sends duplicates right).
#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *left, *right;
};

struct node* insert(struct node *root, int key) {
    if (root == NULL) {
        struct node *p = malloc(sizeof(struct node));
        p->data = key; p->left = p->right = NULL;
        return p;
    }
    if (key < root->data)
        root->left = insert(root->left, key);
    else
        root->right = insert(root->right, key);   /* duplicates go right */
    return root;
}

struct node* search(struct node *root, int key) {
    while (root != NULL) {
        if (key == root->data) return root;
        root = (key < root->data) ? root->left : root->right;
    }
    return NULL;
}
%%{init: {'theme': 'base', 'look': 'handDrawn', 'themeVariables': {'fontFamily': "'Nunito', sans-serif", 'fontSize': '17px', 'primaryColor': '#EFEAD6', 'primaryBorderColor': '#0F766E', 'lineColor': '#23211C'}}}%%
flowchart TD
    R[50 root] --> L[30]
    R --> RR[70]
    L --> LL[20]
    L --> LR[40]

Insertion table for 50,30,70,20,40:

Key Comparison path Attachment
50 empty tree becomes root
30 30 < 50 → left of 50 left child
70 70 > 50 → right of 50 right child
20 20 < 50 → left; 20 < 30 → left left child of 30
40 40 < 50 → left; 40 > 30 → right right child of 30

3.2 Python version

class Node:
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None

def insert(root, key):
    if root is None:
        return Node(key)
    if key < root.data:
        root.left = insert(root.left, key)
    else:
        root.right = insert(root.right, key)
    return root

def search(root, key):
    while root is not None:
        if key == root.data:
            return True
        root = root.left if key < root.data else root.right
    return False

Cost: insertion and search both follow one root-to-leaf path, so each is O(h), where h is the tree height. A balanced tree has h = O(log n); a degenerate tree built from sorted input has h = O(n) and behaves like a linked list.

Examiner Tip: Draw the tree after every insertion in a trace question. The examiner can then award marks for the comparison path even if a pointer line is missing. Also state the duplicate rule in one sentence.


4. Inorder and Preorder Traversal Trace

Traversal visits every node exactly once. Inorder visits left subtree, node, right subtree. Preorder visits node, left subtree, right subtree. For a BST, inorder always produces keys in ascending order—this is the fastest way to check a BST trace.

Traversal Visit order Result for the example BST Main use
Inorder left → root → right 20, 30, 40, 50, 70 Sorted key listing
Preorder root → left → right 50, 30, 20, 40, 70 Copying a tree / prefix display

Recursive code:

void inorder(struct node *root) {
    if (root == NULL) return;
    inorder(root->left);
    printf("%d ", root->data);
    inorder(root->right);
}

void preorder(struct node *root) {
    if (root == NULL) return;
    printf("%d ", root->data);
    preorder(root->left);
    preorder(root->right);
}

Python one-liner shape:

def inorder(root):
    return [] if root is None else inorder(root.left) + [root.data] + inorder(root.right)

def preorder(root):
    return [] if root is None else [root.data] + preorder(root.left) + preorder(root.right)

Trace by descent: for preorder, print 50, descend left to 30, print 30, descend left to 20, print 20, return to 30 and print 40, then return to 50 and print 70. For inorder, descend to the leftmost node 20 first, print it, then 30, then 40, then 50, then 70.

Examiner Tip: In an inorder question on a BST, check the answer immediately for sorted order. If the printed list is not sorted, either the BST insertion or the traversal is wrong—fix it before writing the final answer.


5. Graph — Vertex, Edge, Directed/Undirected and Adjacency List

Vertex: a node of a graph. Edge: a link between two vertices. In an undirected graph A-B has no direction and means B is in adj[A] and A is in adj[B]. In a directed graph A→B is one-way and only B appears in adj[A].

Feature Undirected graph Directed graph
Edge notation A-B A→B
Adjacency entry Both endpoints Only source → destination
Degree One degree count in-degree and out-degree
Max edges on n vertices n(n-1)/2 n(n-1)
Real connect Friendship in social network Follow relationship on a social platform

Adjacency list representation: for each vertex, store a list of its neighbours. It is compact for sparse graphs (few edges) and makes neighbour iteration fast.

# Undirected graph from edges A-B, A-C, B-D, C-E
adj = {}
for v in "ABCDE":
    adj[v] = []
for u, v in [("A","B"), ("A","C"), ("B","D"), ("C","E")]:
    adj[u].append(v)
    adj[v].append(u)

print(adj)
# {'A': ['B','C'], 'B': ['A','D'], 'C': ['A','E'], 'D': ['B'], 'E': ['C']}

Insertion of a new edge D-E:

adj["D"].append("E")
adj["E"].append("D")   # omit this line if the graph is directed
%%{init: {'theme': 'base', 'look': 'handDrawn', 'themeVariables': {'fontFamily': "'Nunito', sans-serif", 'fontSize': '17px', 'primaryColor': '#EFEAD6', 'primaryBorderColor': '#0F766E', 'lineColor': '#23211C'}}}%%
flowchart TD
    A((A)) --- B((B))
    A --- C((C))
    B --- D((D))
    C --- E((E))
Representation Space Check if u-v exists Add edge
Adjacency list O(V+E) O(degree u) O(1) append
Adjacency matrix O(V²) O(1) O(1) assignment

Examiner Tip: Google Maps is a weighted graph: edge weights are distances or travel times. If asked why an adjacency list is preferred for a map, say most intersections have only a few roads, so O(V+E) space beats a dense O(V²) matrix.


6. BFS and DFS — Trace on a Small Graph (5– 6 Nodes)

BFS (Breadth-First Search) starts at a vertex, visits all neighbours, then their neighbours, using a FIFO queue. DFS (Depth-First Search) follows one branch as far as possible before backtracking, using a LIFO stack or recursion.

Graph: vertices A,B,C,D,E; undirected edges A-B, A-C, B-D, C-E.

6.1 BFS trace with a queue

Step Queue front → back Visit Action
1 [A] A enqueue B, C
2 [B,C] B enqueue D
3 [C,D] C enqueue E
4 [D,E] D no new neighbour
5 [E] E no new neighbour

BFS order: A, B, C, D, E. The visited set prevents A from being enqueued again when B and C are examined.

from collections import deque

def bfs(adj, start):
    seen = {start}
    q = deque([start])
    order = []
    while q:
        v = q.popleft()
        order.append(v)
        for nxt in sorted(adj[v]):
            if nxt not in seen:
                seen.add(nxt)
                q.append(nxt)
    return order

# bfs(adj, 'A') -> ['A','B','C','D','E']

6.2 DFS trace with recursion

def dfs(adj, v, seen=None, order=None):
    if seen is None: seen = set()
    if order is None: order = []
    seen.add(v)
    order.append(v)
    for nxt in sorted(adj[v]):
        if nxt not in seen:
            dfs(adj, nxt, seen, order)
    return order

# dfs(adj, 'A') -> ['A','B','D','C','E']

DFS order: A, B, D, C, E when neighbours are processed alphabetically. Start at A, go to B, then D; D has no unvisited neighbour, so backtrack to A and go to C, then E.

Feature BFS DFS
Structure used Queue (FIFO) Stack / recursion (LIFO)
Visit pattern Level by level Branch by branch
Shortest path in unweighted graph Yes Not guaranteed
Space O(V) frontier O(V) depth
Real connect Social-network “friends within 2 hops” File-system search, maze solving

Both traversals are O(V+E) because each vertex is enqueued/pushed once and each edge is examined a constant number of times.

Examiner Tip: Always write the neighbour order you assumed. For an undirected graph stored as lists, the order depends on insertion order; using sorted(adj[v]) makes the answer deterministic and lets the marker follow the trace.


7. Real Connect Summary

Syllabus phrase Concrete interpretation
File system = tree Root folder → subfolders → files; each item has one parent
BST in database indexing Keys stored in a balanced tree; search follows one path in O(log n)
Google Maps = weighted graph Intersections are vertices; roads are weighted edges (distance/time)
Social network = graph People are vertices; friendships/follows are edges, cycles are normal
Decision Tree in ML = binary tree Each internal node asks a yes/no test; each leaf gives a class label
%%{init: {'theme': 'base', 'look': 'handDrawn', 'themeVariables': {'fontFamily': "'Nunito', sans-serif", 'fontSize': '17px', 'primaryColor': '#EFEAD6', 'primaryBorderColor': '#0F766E', 'lineColor': '#23211C'}}}%%
flowchart TD
    A[Raw data] --> B[Decision Tree: yes/no splits]
    B --> C[Leaf: predicted class]
    D[Map intersection] --> E[Weighted graph]
    E --> F[Shortest path via BFS/Dijkstra]
    G[Database key] --> H[BST index]
    H --> I[O(log n) lookup]

8. Predicted Exam-Ready Questions (Solved — Not Verbatim PYQs)

Predicted Q1 (2 Marks | Binary Tree Terminology)

Q (predicted from “Binary tree — terminology (root, leaf, height, level)”): Define root, leaf, level and height with reference to a binary tree.

Solution: The root is the only node with no parent. A leaf has no children. The level is the edge distance from the root (root = level 0). The height is the number of edges on the longest root-to-leaf path. In the tree 50→(30,70), 30→(20,40), the root is 50, leaves are 20/40/70, level 1 contains 30 and 70, and height is 2.


Predicted Q2 (5 Marks | Properties)

Q (predicted from “properties”): State three properties of a binary tree and verify them for a 5-node tree of height 2.

Solution:

  1. A tree with n nodes has exactly n-1 edges; here 5-1 = 4.
  2. Level i has at most 2^i nodes; level 2 has at most 4 nodes, and this tree uses 2 of them.
  3. A perfect tree of height h has 2^(h+1)-1 nodes; for h=2 that is 7, so a 5-node tree is not perfect. Extra: a BST's inorder list is sorted, which gives a quick validity check.

Predicted Q3 (7 Marks | BST Insert and Traversal Trace)

Q (predicted from assignment “Draw BST after inserting 50, 30, 70, 20, 40” and “Write inorder and preorder of above BST”): Insert 50, 30, 70, 20, 40 into an initially empty BST. Draw the final tree and write its inorder and preorder traversals.

Solution: Insertion table from Section 3. Final tree:

        50
       /  \
     30    70
    /  \
  20    40

Inorder: 20, 30, 40, 50, 70 (left-root-right; sorted as expected for a BST).
Preorder: 50, 30, 20, 40, 70 (root-left-right).
Each comparison during insertion costs O(1); total insertion cost is O(h) per key, here O(2) for the last keys.


Predicted Q4 (7 Marks | BST Insert and Inorder in Python)

Q (predicted from assignment “BST insert and inorder in python”): Write Python code to insert 50, 30, 70, 20, 40 into a BST and print its inorder traversal.

Solution:

class Node:
    def __init__(self, key):
        self.data = key
        self.left = self.right = None

def insert(root, key):
    if root is None:
        return Node(key)
    if key < root.data:
        root.left = insert(root.left, key)
    else:
        root.right = insert(root.right, key)
    return root

def inorder(root):
    if root is None:
        return []
    return inorder(root.left) + [root.data] + inorder(root.right)

root = None
for key in [50, 30, 70, 20, 40]:
    root = insert(root, key)
print(inorder(root))   # [20, 30, 40, 50, 70]

The recursive insert returns the (possibly new) subtree root so the parent link can be assigned. The inorder list is sorted, confirming the BST property.


Predicted Q5 (7 Marks | Search in BST)

Q (predicted from “Binary Search Tree — insert” + “search”): In the BST of Q3, search for 40 and for 25. Show the comparison path and state the cost.

Solution:

  • Search 40: compare with 50 → go left; compare with 30 → go right; compare with 40 → found. Path 50 → 30 → 40, 3 comparisons.
  • Search 25: compare with 50 → left; compare with 30 → left; compare with 20 → 25 > 20 → right; right child is NULL → not found. Path 50 → 30 → 20 → NULL, 3 comparisons plus a null check.

Search cost is O(h). For this balanced 5-node tree, h = 2; in a degenerate tree of the same size it could be O(5). This is why database indexes keep trees balanced.


Predicted Q6 (7 Marks | Graph as Adjacency List in Python Dict)

Q (predicted from assignment “Graph as adjacency list in Python dict”): Represent the undirected graph with edges A-B, A-C, B-D, C-E as a Python dictionary of adjacency lists. Show how to insert edge D-E.

Solution:

adj = {}
for v in "ABCDE":
    adj[v] = []
for u, v in [("A","B"), ("A","C"), ("B","D"), ("C","E")]:
    adj[u].append(v)
    adj[v].append(u)          # both directions for undirected graph

print(adj)
# {'A': ['B','C'], 'B': ['A','D'], 'C': ['A','E'], 'D': ['B'], 'E': ['C']}

adj["D"].append("E")
adj["E"].append("D")          # second append needed only for undirected
print(adj["D"], adj["E"])     # ['B','E'] ['C','D']

Space is O(V+E) = O(5+4) = O(9) entries; adding one edge is O(1) per list append.


Predicted Q7 (7 Marks | BFS Using Queue in Python)

Q (predicted from assignment “BFS using queue in Python (10–15 lines) BFS from A on: A-B, A-C, B-D, C-E”): Write a Python BFS function using a queue and give the visit order starting from A.

Solution:

from collections import deque

def bfs(adj, start):
    seen = {start}
    q = deque([start])
    order = []
    while q:
        v = q.popleft()
        order.append(v)
        for nxt in sorted(adj[v]):
            if nxt not in seen:
                seen.add(nxt)
                q.append(nxt)
    return order

adj = {'A':['B','C'], 'B':['A','D'], 'C':['A','E'], 'D':['B'], 'E':['C']}
print(bfs(adj, 'A'))   # ['A', 'B', 'C', 'D', 'E']

The seen set is added at enqueue time, not at dequeue time; otherwise a vertex could be queued twice from two parents. Complexity is O(V+E).


Predicted Q8 (5 Marks | DFS Trace and BFS Comparison)

Q (predicted from “BFS and DFS — trace on a small graph (5– 6 nodes)”): For the same graph, give DFS order from A with alphabetical neighbours and compare it with BFS.

Solution: DFS follows A → B → D; D has no unvisited neighbour, so it backtracks to A, then visits C → E. Order: A,B,D,C,E. BFS order is A,B,C,D,E. Both are O(V+E). DFS uses a stack/recursion and may go deep on one branch; BFS uses a queue and guarantees the fewest edges to each vertex in an unweighted graph.


Predicted Q9 (2 Marks | Real Connect Identification)

Q (predicted from “Real connect: File system = tree”, “BST in database indexing”, “Google Maps = weighted graph”, “Social network = graph”, “Decision Tree in ML = binary tree”): Classify each application as a tree or a graph and give one reason.

Solution: File system = tree (one parent per folder). Decision Tree in ML = binary tree (yes/no splits). Database index = balanced BST (ordered keys, O(log n) lookup). Google Maps = weighted graph (roads carry distance/time weights). Social network = graph (many friends and cycles).


9. Practice Questions (Self-Test)

  1. (2 Marks) How many edges does a tree with 12 nodes have? (Ans: 11.)
  2. (7 Marks) Insert 10, 20, 5, 15, 30 into a BST and write inorder and preorder traversals.
  3. (7 Marks) Search for 25 in the BST of Q3 and state each comparison.
  4. (7 Marks) Build an undirected adjacency list for A-B, B-C, C-D, D-A, A-E and insert edge C-E.
  5. (7 Marks) Run DFS and BFS from A on the Q4 graph used in Section 6 and explain why the orders differ.