Courses / Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course
2.3 Trees: Binary Trees, BST, Traversals, DFS and BFS
Unit 2 – Computational Thinking and Algorithms · 100 min read · 10 MCQs to check yourself
Abdul Bari – binary tree traversals (in-order, pre-order, post-order)
1. What is a tree?
A tree is a hierarchical (non-linear) data structure made of nodes joined by edges.
| Term | Meaning |
|---|---|
| Root | The top node (no parent) |
| Parent / child | A node directly above / below another |
| Siblings | Children of the same parent |
| Leaf | A node with no children |
| Subtree | A node with all its descendants |
| Level / depth | Distance from the root (root = level 0) |
| Height | Number of levels on the longest path from root to a leaf |
| Binary tree | Every node has at most two children: left and right |
2. Binary search tree (BST)
In a BST, for every node: all values in the left subtree are smaller and all values in the right subtree are larger. Insert 50, 30, 70, 20, 40, 60, 80 in that order:
Searching a balanced BST is fast – at each node we go left or right and ignore half the tree – about O(log n).
3. Tree traversal – visiting every node once
| Traversal | Order | Memory trick |
|---|---|---|
| Pre-order | Root → Left → Right | Root comes pre (first) |
| In-order | Left → Root → Right | Root in the middle |
| Post-order | Left → Right → Root | Root comes post (last) |
Example 1 (model paper): tree with A at the root; B (left) has children D and E; C (right) has a right child F – the first tree above.
- Pre-order: A B D E C F
- In-order: D B E A C F
- Post-order: D E B F C A
Example 2 (BST above):
- In-order: 20 30 40 50 60 70 80 ← an in-order traversal of a BST always gives sorted order.
- Pre-order: 50 30 20 40 70 60 80
- Post-order: 20 40 30 60 80 70 50
class Node:
def __init__(self, value):
self.value, self.left, self.right = value, None, None
def insert(root, value):
if root is None:
return Node(value)
if value < root.value:
root.left = insert(root.left, value)
else:
root.right = insert(root.right, value)
return root
def inorder(n): return inorder(n.left) + [n.value] + inorder(n.right) if n else []
def preorder(n): return [n.value] + preorder(n.left) + preorder(n.right) if n else []
def postorder(n): return postorder(n.left) + postorder(n.right) + [n.value] if n else []
root = None
for v in [50, 30, 70, 20, 40, 60, 80]:
root = insert(root, v)
print("In-order: ", inorder(root))
print("Pre-order: ", preorder(root))
print("Post-order:", postorder(root))
Output:
In-order: [20, 30, 40, 50, 60, 70, 80]
Pre-order: [50, 30, 20, 40, 70, 60, 80]
Post-order: [20, 40, 30, 60, 80, 70, 50]
4. Searching a tree: DFS and BFS
- Depth-First Search (DFS) goes deep down one branch before backtracking (uses a stack or recursion). Pre-order is a DFS.
- Breadth-First Search (BFS) visits level by level (uses a queue).
Worked example (model paper Q6): find Security in the company hierarchy.
| Method | Order of visits until Security is found |
|---|---|
| DFS (left first) | CEO → CTO → Eng → DevOps → IT → Security (6 visits) |
| BFS (level by level) | CEO → CTO → CFO → Eng → IT → Finance → DevOps → Security (8 visits) |
Here DFS is quicker because Security is deep on the left side; BFS is better when the target is near the top (e.g. finding CFO: BFS needs 3 visits, DFS needs 6).
from collections import deque
org = {"CEO": ["CTO", "CFO"], "CTO": ["Eng", "IT"], "CFO": ["Finance"],
"Eng": ["DevOps"], "IT": ["Security"], "Finance": [], "DevOps": [], "Security": []}
def dfs(start, target):
stack, visited = [start], []
while stack:
node = stack.pop()
visited.append(node)
if node == target:
return visited
stack.extend(reversed(org[node])) # left child is explored first
return visited
def bfs(start, target):
queue, visited = deque([start]), []
while queue:
node = queue.popleft()
visited.append(node)
if node == target:
return visited
queue.extend(org[node])
return visited
print("DFS:", " -> ".join(dfs("CEO", "Security")))
print("BFS:", " -> ".join(bfs("CEO", "Security")))
Output:
DFS: CEO -> CTO -> Eng -> DevOps -> IT -> Security
BFS: CEO -> CTO -> CFO -> Eng -> IT -> Finance -> DevOps -> Security
5. Applications of trees
- File systems: folders inside folders.
- Organisation charts and family trees.
- Binary search trees: fast searching, inserting and deleting sorted data (dictionaries, database indexes – B-trees).
- HTML DOM: a web page is a tree of tags.
- Decision trees in machine learning; game trees in chess AI.
- Expression trees in compilers:
(3 + 4) * 5.
Short and long questions
1. Construct a binary search tree by inserting 40, 20, 60, 10, 30, 50, 70, 25. Write its in-order, pre-order and post-order traversals and explain one property you notice. (2 + 3 + 1)
Model answer
BST (2): 40 is the root; left 20 (left 10, right 30, and 30 has left child 25); right 60 (left 50, right 70).
Traversals (3):
- In-order (L, Root, R): 10 20 25 30 40 50 60 70
- Pre-order (Root, L, R): 40 20 10 30 25 60 50 70
- Post-order (L, R, Root): 10 25 30 20 50 70 60 40
Property (1): the in-order traversal of a BST lists the values in ascending sorted order; also the root is first in pre-order and last in post-order.
2. A company manages its organisational hierarchy using a tree: CEO has children CTO and CFO; CTO has Eng and IT; CFO has Finance; Eng has DevOps; IT has Security. The company wants to find the Security department. (a) Search Security using DFS and BFS. (b) Outline the sequence of node visits in the selected search method. (3 + 3)
Model answer
(a) Searching (3):
- DFS (stack, explore left branch fully first): CEO → CTO → Eng → DevOps → (backtrack) IT → Security – found after 6 visits.
- BFS (queue, level by level): level 0 CEO; level 1 CTO, CFO; level 2 Eng, IT, Finance; level 3 DevOps, Security – found after 8 visits. Selected method: DFS, because Security is deep in the left half of the tree, so DFS reaches it with fewer visits.
(b) Sequence for DFS (3):
| Step | Stack (top at right) | Visit |
|---|---|---|
| 1 | [CEO] | CEO |
| 2 | [CFO, CTO] | CTO |
| 3 | [CFO, IT, Eng] | Eng |
| 4 | [CFO, IT, DevOps] | DevOps |
| 5 | [CFO, IT] | IT |
| 6 | [CFO, Security] | Security – found |
3. Write any three applications of the tree data structure.
Model answer
- File systems – folders and sub-folders. 2. Organisation charts / hierarchies. 3. Binary search trees and database indexes (B-trees) for fast searching. (Also: HTML DOM, decision trees in AI, expression trees in compilers.)
4. Differentiate between DFS and BFS (any three points).
Model answer
| DFS | BFS |
|---|---|
| Goes deep down one branch before backtracking | Visits nodes level by level |
| Uses a stack (or recursion) | Uses a queue |
| Good when the target is deep / to explore whole paths | Good for nearest/shortest path or targets near the top |
5. Insert 45, 25, 65, 15, 35, 55, 75 into a binary search tree and write its pre-order and post-order traversals.
Model answer
Tree: root 45; left 25 (children 15, 35); right 65 (children 55, 75).
- Pre-order (Root, L, R): 45 25 15 35 65 55 75
- Post-order (L, R, Root): 15 35 25 55 75 65 45 (In-order would be 15 25 35 45 55 65 75 – sorted.)
6. A company needs to store hierarchical employee data. Which data structure would you recommend, and how would you apply it? (1 + 2)
Model answer
Tree (1). Apply it by making the CEO the root, managers as children and their staff as grandchildren; each node stores the employee’s details and a list of children (2). Reporting lines are parent–child links; DFS/BFS can find any employee and the subtree of a node gives a whole department.
7. Define the following tree terms: root, leaf, parent, sibling, height, binary tree.
Model answer
- Root: top node with no parent. Leaf: node with no children. Parent: node directly above another.
- Siblings: nodes with the same parent. Height: number of levels on the longest root-to-leaf path.
- Binary tree: tree in which every node has at most two children (left and right).
8. Perform the in-order traversal and write the correct sequence of node visits for the tree: A is the root with children B (left) and C (right); B has children D and E; C has right child F.
Model answer
In-order = Left → Root → Right. Left subtree of A (rooted at B): D, B, E → root A → right subtree (rooted at C): C, F. Sequence: D B E A C F
This lesson ends with a quiz of 10 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: 2.2 Data Structures: Lists, Arrays, Stacks and Queues · Next: 2.4 Binary Search: Algorithm, Tracing and Applications
All lessons in Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course