0% found this document useful (0 votes)
21 views20 pages

Lecture 1

The document provides a comprehensive overview of trees as a data structure in computer science, explaining their hierarchical nature and terminology such as root, node, edge, and leaf. It discusses various types of trees, including general trees, binary trees, binary search trees, and balanced trees, along with their real-world analogies and applications. Additionally, it covers tree traversal techniques like depth-first and breadth-first traversal, emphasizing their importance in processing tree structures.

Uploaded by

AIKO.J Breezy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views20 pages

Lecture 1

The document provides a comprehensive overview of trees as a data structure in computer science, explaining their hierarchical nature and terminology such as root, node, edge, and leaf. It discusses various types of trees, including general trees, binary trees, binary search trees, and balanced trees, along with their real-world analogies and applications. Additionally, it covers tree traversal techniques like depth-first and breadth-first traversal, emphasizing their importance in processing tree structures.

Uploaded by

AIKO.J Breezy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Trees

SCHOOL OF TECHNOLOGY
Computer Science : Year 2

Module : Data Structures and Algorithm 2


Prepared By Alpha Omar Leigh (BSc, MSc)

Page 1 of 20
Trees

🌳 Introduction to Trees Data Structure

Introduction to Trees
In computer science, a tree is a non-linear data structure used to represent hierarchical
relationships. Unlike arrays, stacks, or queues (which are linear), trees branch out in
multiple directions.Imagine a tree data structure like a family tree or an organization
chart: at the top, there's a single "root" node representing the starting point or main idea.
From that root, branches extend downwards to child nodes, which are like family
members or departments, each connecting to their own smaller branches. These
connections form a clear hierarchy, with every node accessible through its parent, making
it easy to trace pathways from the top to any specific leaf — or endpoint — in the
structure. Think of it as a family tree showing how everything is connected in a neat,
branching way!

📌 Real-World Analogy: Biological Taxonomy


The tree structure used in biology to classify organisms — from Kingdom down to
Species — is a perfect real-world example. It helps organize data in a logical, layered way.

Below is a taxonomy tree starting from the kingdom Animalia, classifying living organisms
into more specific groups:

Page 2 of 20
Trees

Tree Terminology (Aligned to the Image)


🔹 Root
Definition: The topmost node with no parent.
Example: Animalia

🔹 Node
Definition: A data element in the tree.
Example: Mammal , Felidae , Homo , and Sapiens are all nodes.

Page 3 of 20
Trees

🔹 Edge
Definition: The connection between a parent and child.
Example: The line from Mammal to Primate represents an edge.

🔹 Parent and Child


Parent: A node that has at least one child.
Child: A node that comes from a parent.
Examples:
Mammal is the parent of Primate and Carnivora .

Felis is the parent of Domestica (House Cat) and Leo (Lion).

🔹 Siblings
Definition: Nodes that share the same parent.
Examples:
Domestica and Leo are siblings.

Homo and Pan are siblings.

🔹 Leaf
Definition: A node with no children.
Examples:
Sapiens (Human), Troglodytes (Chimpanzee), Domestica (House
Cat), Leo (Lion), and Domestica (Housefly) are all leaf nodes.

🔹 Subtree
Definition: A smaller tree within a bigger one, starting from any node.
Example: The entire branch starting from Primate is a subtree.

Page 4 of 20
Trees

🔹 Depth
Definition: The number of edges from the root to the node.

Node Depth
Animalia 0

Chordate 1

Mammal 2

Primate 3

Hominidae 4

Homo 5

Sapiens 6

✅ Note: Depth increases as we move down the tree.

🔹 Height
Definition: The number of edges on the longest path from a node to a leaf node.

Node Height
Animalia 6

Chordate 5

Mammal 4

Primate 3

Hominidae 2

Homo 1

Sapiens 0

✅ Note: Height decreases as we move down to leaves.

🔹 Level
Definition: The group of nodes at the same depth.
Page 5 of 20
Trees

Level Nodes
0 Animalia

1 Chordate, Arthropoda

2 Mammal, Insect

3 Primate, Carnivora, Diptera

4 Hominidae, Felidae, Musca

5 Homo, Pan, Felis

6 Sapiens, Troglodytes, Domestica, Leo, Domestica (fly)

🌐 Why Trees Are Important


Trees are used in many areas of computing:

File systems – Directory structures on your computer.


Databases – Indexing using B-trees or binary search trees.
Artificial Intelligence – Decision trees.
Networking – Routing paths.
Hierarchical classifications – Like taxonomy trees!

✍️ Practice Questions
1. What is the depth of Musca ?

2. What is the height of Mammal ?


3. Name two leaf nodes under Felidae .

4. What is the parent of Troglodytes ?

Labeled vs. Unlabeled Trees


Trees in data structures can be either labeled or unlabeled, depending on whether their
nodes carry unique data or anonymous structure.

Page 6 of 20
Trees

🔖 Labeled Trees
✅ What Is It?
A labeled tree is a tree where each node has a unique name or value. These labels help us
distinguish one node from another.

💡 Real-Life Example:
A family tree is labeled — each person has a name (like "Grandma", "Dad", "You").

text
Grandma
└── Dad
├── You
└── Sister

Every person (node) is different and identified by their name.

🔢 Formula (Cayley’s Formula):


The number of different labeled trees you can create with n labeled nodes:

n−2
Total labeled trees = n

🧮 Example:
If you have 4 labeled nodes (say, A, B, C, D), the total number of labeled trees is:

4−2 2
4 = 4 = 16

So, you can make 16 different trees using 4 uniquely labeled nodes.

🚫 Unlabeled Trees
✅ What Is It?
An unlabeled tree is a tree where the nodes are not uniquely named. You only care about
the shape or structure of the tree — not the identity of nodes.

Page 7 of 20
Trees

💡 Real-Life Example:
Imagine an organization chart where we only care about the roles (e.g., Manager →
Employee), but we don't know who exactly the people are.

text

└── •
├── •
└── •

Each dot ( • ) is a node, but we don’t know or care which is which — we only care about
how they connect.

🔢 Formula (Catalan Number):


For binary trees with n nodes (unlabeled), the number of possible shapes is:

(2n)!
Cn =
(n + 1)! ⋅ n!

This is called the Catalan Number.

🧮 Example:
If you have 3 nodes, the number of possible unlabeled binary trees is:

(2×3)! 6! 720
C3 = = = = 5
(3 + 1)!×3! 4!×3! 24×6

So, you can make 5 different binary tree structures with 3 anonymous nodes.

🧠 Quick Recap Table


Feature Labeled Tree Unlabeled Tree
Node Identity Each node has a unique label Nodes have no names

Example Family tree with names Tree structure without labels

Focus Labels + Structure Only Structure

Formula n
n−2
(Cayley) Catalan Numbers

Page 8 of 20
Trees

🏫 Classwork Activities
✍️ Exercise 2: Apply Cayley’s Formula
Question: How many labeled trees can you create with:
3 nodes
6 nodes

✍️ Exercise 3: Use Catalan Numbers


Use the formula:

(2n)!
Cn =
(n + 1)! ⋅ n!

Questions:
1. How many unlabeled binary trees can be formed with:

2 nodes?
4 nodes?

🌳
Types of Trees in Data Structures
Understanding tree types helps us solve problems faster — just like knowing the types of
buildings helps you find a hospital vs. a school. Let’s look at each tree type, with simple
definitions and examples:

🌲 General Tree
Definition: A tree where each node can have any number of children.

🔹 Real-Life Analogy:
Think of a family: A parent can have 1 child, 2 children, or 10!
Page 9 of 20
Trees

✅ Key Point:
No rules on how many children a node must have.

🖼️ Example:
text
A
/ | \
B C D
/ \
E F

Node A has 3 children (B, C, D)

Node C has 2 children (E, F)

🌳 Binary Tree
Definition: Each node can have at most 2 children — usually called left and
right.

🔹 Real-Life Analogy:
Think of a yes/no question flowchart: every step leads to 2 choices only — Yes or No.

✅ Key Point:
Each node has 0, 1, or 2 children.
Helps organize data in a structured way.

🖼️ Example:
text
A
/ \
B C
/ \
D E

Page 10 of 20
Trees

🔍 Binary Search Tree (BST)


Definition: A special binary tree where values follow a specific order:

Left child ≤ Parent ≤ Right child

🔹 Real-Life Analogy:
Think of a dictionary:

Left page has earlier words.


Right page has later words.

✅ Key Point:
Helps in fast searching (like binary search).
Always sorted automatically.

🖼️ Example:
text
8
/ \
4 10
/ \ \
2 6 12

4 is less than 8 → left


10 is more than 8 → right
6 is more than 4 but less than 8 → right of 4

⚖️ Balanced Trees
Definition: Trees that keep their height small to make searching faster.

🔹 Real-Life Analogy:
Imagine searching books on shelves. If the shelf is tall and thin, you climb more. If it's
short and wide, you find books faster.
Page 11 of 20
Trees

✅ Key Point:
Designed to stay “not too tall”.

Examples:

AVL Tree
Red-Black Tree

🖼️ Unbalanced vs Balanced:
text
Unbalanced BST: Balanced Tree:
1 4
\ / \
2 2 6
\ / \ / \
3 1 3 5 7

Unbalanced = long one-sided chain → slow!


Balanced = even structure → fast lookup!

✅ Summary Table
Tree Type Children per Special Rule Use Case
Node
General Tree Any number None Family tree, HTML
DOM

Binary Tree 0, 1, or 2 Max 2 children Arithmetic


expressions

Binary Search 0, 1, or 2 Left ≤ Parent ≤ Right Searching/sorting


Tree

Balanced Tree 0, 1, or 2 Balanced height for faster Databases, Maps,


operations Sets

Great! Here are 5 multiple-choice questions (MCQs) based on the Types of Trees — clear,
beginner-friendly, and perfect for classroom or homework use.

Page 12 of 20
Trees

📝 Classwork: MCQs on Types of Trees


Question 1:
Which of the following is true about a Binary Tree?

A. Each node must have exactly 2 children


B. Each node can have at most 2 children
C. Each node can have any number of children
D. It is always balanced

✅ Answer: B. Each node can have at most 2 children

Question 2:
In a Binary Search Tree (BST), where is a node with a larger value than the parent usually
placed?

A. To the left
B. To the right
C. Anywhere
D. At the root

Question 3:
Which of these trees is designed to maintain a low height for efficient searching?

A. General Tree
B. Binary Tree
C. Balanced Tree
D. Family Tree

Question 4:
Which type of tree allows each node to have any number of children?

A. Binary Tree
B. Binary Search Tree
Page 13 of 20
Trees

C. Balanced Tree
D. General Tree

Question 5:
What is a real-world example of a General Tree?

A. A flowchart with two options at each step


B. A file system with folders and subfolders
C. A list of sorted numbers
D. A dictionary with alphabetical order

🌳 Tree Traversal Techniques


A tree traversal means visiting all the nodes of a tree in a specific order. This
helps in understanding or processing the tree's structure and data.

We’ll use the book structure in the image as our example.

🔍 Depth-First Traversal (DFS)


DFS explores as far as possible down a branch before backtracking.
Page 14 of 20
Trees

There are three main types:

📌 A. Pre-order Traversal
Visit Order: Root → Left Subtree → Right Subtree

For our book tree:


1. Start with Book

2. Go to Chapter1 , then Section 1.1 , then Section 1.2


3. From Section 1.2 , visit Section 1.2.1 then Section 1.2.2

4. Go back and visit Chapter2

5. Then Section 2.1 , Section 2.2 , followed by Section 2.2.1 and


Section 2.2.2

✔ Traversal Order: Book → Chapter1 → Section 1.1 → Section 1.2 → Section


1.2.1 → Section 1.2.2 → Chapter2 → Section 2.1 → Section 2.2 → Section
2.2.1 → Section 2.2.2

📌 B. In-order Traversal
Visit Order: Left Subtree → Root → Right Subtree

⚠️ Note: In-order traversal is most useful for Binary Search Trees because it
returns nodes in sorted order. Our tree isn’t binary, so in-order isn't as
meaningful here, but here’s the logic:

1. For each node, go as far left as possible


2. Then visit the current node
3. Then go right

✔ In our case, in-order would only apply meaningfully if each node had exactly 2
children, which it doesn’t. So it’s not commonly used for general trees like the book
structure.

📌 C. Post-order Traversal
Visit Order: Left Subtree → Right Subtree → Root
Page 15 of 20
Trees

For our book tree:


1. Start with leftmost leaf nodes: Section 1.1 , Section 1.2.1 , Section
1.2.2

2. Then visit Section 1.2 , then Chapter1

3. Move to Section 2.1 , Section 2.2.1 , Section 2.2.2


4. Then Section 2.2 , then Chapter2

5. Finally visit Book

✔ Traversal Order: Section 1.1 → Section 1.2.1 → Section 1.2.2 → Section


1.2 → Chapter1 → Section 2.1 → Section 2.2.1 → Section 2.2.2 → Section
2.2 → Chapter2 → Book

🌐 Breadth-First Traversal (BFS)


Also known as Level-order Traversal.

Visit nodes level by level, from top to bottom, left to right.


For our book tree:
1. First level: Book

2. Second level: Chapter1 , Chapter2


3. Third level: Section 1.1 , Section 1.2 , Section 2.1 , Section 2.2

4. Fourth level: Section 1.2.1 , Section 1.2.2 , Section 2.2.1 , Section


2.2.2

✔ Traversal Order: Book → Chapter1 → Chapter2 → Section 1.1 → Section 1.2


→ Section 2.1 → Section 2.2 → Section 1.2.1 → Section 1.2.2 → Section
2.2.1 → Section 2.2.2

🔑 Summary Table:
Traversal Type Visit Order Good For
Pre-order (DFS) Root → Left → Right Copying trees, prefix
expression

Page 16 of 20
Trees

Traversal Type Visit Order Good For


In-order (DFS) Left → Root → Right BST (sorted values)

Post-order Left → Right → Root Deleting trees, postfix


(DFS) expression

Breadth-First Level-by-level (Top to Bottom, Left Shortest path, organization


(BFS) to Right) charts

Example

Key Notes About the Tree


1. Root Node: A
2. Left Subtree of A: B → C → D, E

3. Right Subtree of A: F → G → H, I
4. Leaves: D, E, H, I (nodes with no children).

Page 17 of 20
Trees

Tree Traversals (Step-by-Step)


1. Breadth-First Traversal (BFS)
Rule: Visit nodes level by level, left to right.
Order:
1. Level 0: A
2. Level 1: B → F
3. Level 2: C → G
4. Level 3: D → E → H → I

Final BFS Order:


A→B→F→C→G→D→E→H→I

2. Depth-First Traversal (DFS)


a. Pre-Order (Root → Left → Right)
Rule: Visit the root first, then left subtree, then right subtree.
Path:
1. Start at A (root).
2. Go to B (left child of A), then C (left child of B), then D (left child of C).
3. Backtrack to E (right child of C).
4. Return to A and move to F (right child of A), then G (right child of F), then
H (left child of G), then I (right child of G).
Final Pre-Order:
A→B→C→D→E→F→G→H→I

Page 18 of 20
Trees

b. In-Order (Left → Root → Right)


Rule: Visit left subtree, then root, then right subtree.
Path:
1. Start at A, but first explore its left subtree (B → C → D, E).

From B, go to C, then D (leftmost).


Visit D → C → E → B.

2. Visit A (root).
3. Explore the right subtree (F → G → H, I).

From F, go to G, then H (leftmost).


Visit H → G → I → F.

Final In-Order:
D→C→E→B→A→H→G→I→F

c. Post-Order (Left → Right → Root)


Rule: Visit left subtree, then right subtree, then root.
Path:
1. Start at A, but first explore its left subtree (B → C → D, E).

Visit D → E → C → B.

2. Explore the right subtree (F → G → H, I).

Visit H → I → G → F.

3. Finally, visit A (root).

Final Post-Order:
D→E→C→B→H→I→G→F→A

Summary of Correct Traversals


Traversal Type Order of Nodes Visited
BFS A→B→F→C→G→D→E→H→I

Pre-Order A→B→C→D→E→F→G→H→I

In-Order D→C→E→B→A→H→G→I→F

Page 19 of 20
Trees

Traversal Type Order of Nodes Visited


Post-Order D→E→C→B→H→I→G→F→A

Key Takeaways for Beginners


1. BFS explores the tree level by level.
2. Pre-Order prioritizes the root before children.
3. In-Order processes left, then root, then right (useful for BSTs).
4. Post-Order processes children before the root (used in deletions).

classwork

created with the evaluation version of Markdown Monster

Page 20 of 20

You might also like