day2 srm
day2 srm
"Before we dive into Trees, let's quickly recall Data Structures. We have Linear Data Structures like
Arrays, Linked Lists, Stacks, and Queues. But what if we need something more flexible? This is where
Non-Linear Data Structures come into play."
"Great! In non-linear structures, elements are not stored sequentially. Instead, they maintain
hierarchical relationships. Two key types are Trees and Graphs. Today, we will focus on Trees, one of
the most powerful data structures used in computing."
Introduction to Trees
"A Tree is a hierarchical data structure made up of nodes connected by edges. Unlike a linked list,
where each element points to the next, trees branch out like a real tree."
Example: "Imagine your computer's file system. The root directory contains multiple folders, and
each folder can contain files or subfolders. This structure follows a tree-like pattern."
"Let's visualize a simple family tree. Can someone give an example of a hierarchical relationship in
their family or workplace?"
Root (C:/)
├── Documents
│ ├── Resume.docx
│ ├── Notes.txt
├── Pictures
│ ├── Photo1.jpg
│ ├── Photo2.png
Explain:
Documents and Pictures are child nodes of C: They contain more files (subnodes).
"Can you think of other real-life examples where data is stored in a tree structure?"
(Expected answers: Family Tree, Organization Chart, DOM in HTML, etc.)
Tree Terminology
"Now that we know what trees are, let’s understand some important terms used in tree data
structures."
Term Definition
Interactive Example:
"Let’s draw a simple tree and label the Root, Parent, Child, and Leaf Nodes."
(Show the following tree on the board and ask students to identify components.)
A (Root)
/ \
B C
/\ / \
D E F G
Ask: "What is the root node? What are the leaf nodes? What are the siblings?”
Types of Trees
General
Binary
Ternary
N-ary
1. Full Binary Tree A full Binary tree is a special type of binary tree in which every parent
node/internal node has either two or no children.
2. Perfect Binary Tree A perfect binary tree is a type of binary tree in which every internal node
has exactly two child nodes and all the leaf nodes are at the same level.
3. Complete Binary Tree A complete binary tree is just like a full binary tree, but with two
major differences. Every level must be completely filled. All the leaf elements must lean
towards the left. The last leaf element might not have a right sibling i.e. a complete binary
tree doesn't have to be a full binary tree.
4. Balanced Binary Tree It is a type of binary tree in which the difference between the
height of the left and the right subtree for each node is either 0 or 1.
Binary Trees & Their Properties A Binary Tree is a tree in which each node has at most two children.
This makes it easier to implement and traverse.
10
/ \
5 20
/\
3 7
Complete Binary Tree: All levels are completely filled except possibly the last.
Perfect Binary Tree: A full tree where all leaf nodes are at the same level.
Balanced Binary Tree: The height difference between left and right subtrees is at most 1.
Let's go step by step and visualize how the binary tree is built using the given Python code.
class TreeNode:
self.val = val
self.left = None
self.right = None
if not root:
return TreeNode(val)
If there is no tree (i.e., root is None), we create a new node with the given val and return it.
if not root.left:
root.left = TreeNode(val)
If the left child of the current node is empty, insert the new value there.
root.right = TreeNode(val)
Step 6: If Both Left & Right Are Full, Insert in Left Subtree Recursively
else:
If both left and right children exist, we recursively try inserting into the left subtree.
Visual Representation
Let’s insert values in the order: 10, 20, 30, 40, 50, 60, 70, 80, 90, 100.
10
10
20
10
/ \
20 30
10
/ \
20 30
40
10
/ \
20 30
/ \
40 50
6️⃣ Insert 60 (Left of 40, since 20's left and right are full)
10
/ \
20 30
/ \
40 50
60
10
/ \
20 30
/ \
40 50
/ \
60 70
10
/ \
20 30
/ \
40 50
/ \ /
60 70 80
10
/ \
20 30
/ \
40 50
/ \ /\
60 70 80 90
10
/ \
20 30
/ \
40 50
/ \ /\
60 70 80 90
100
Summary
Root is 10.
Insertion follows the rule: Left first, then right, then recursively left.
This is how the binary tree is built step by step. Let me know if you need more details! 🚀
"Now that we understand trees, we need ways to visit and process each node systematically. These
methods are called Tree Traversals."
Real-Life Example:
"Imagine searching for a book in a large library. There are different ways to search:"
Section-wise: First check the left section, then right (similar to Preorder, Inorder, Postorder).
Ask: "Can you think of other examples where we systematically explore a structure?" (Expected
answers: File system, decision trees, family trees, etc.)
Depth-First Traversal (Preorder, Inorder, Postorder)
"Depth-First Traversal (DFS) explores one branch of a tree completely before moving to another
branch."
Example Tree:
/\
2 3
/\ \
4 5 6
Preorder Output: 1 → 2 → 4 → 5 → 3 → 6
Python Code:
def preorder(root):
if root:
Inorder Output: 4 → 2 → 5 → 1 → 3 → 6
Python Code:
def inorder(root):
if root:
📌 Real-Life Example: "Inorder is used in Binary Search Trees (BSTs) to get sorted data."
Postorder Output: 4 → 5 → 2 → 6 → 3 → 1
Python Code:
def postorder(root):
if root:
In Level Order Traversal, we visit nodes level by level from top to bottom, moving from left to right
at each level.
🌳 Example Tree
/\
2 3
/\ \
4 5 6
5. Traversal is complete! 🎉
class TreeNode:
self.val = val
self.left = None
self.right = None
def level_order(root):
if not root:
return
while queue:
queue.append(node.left)
if node.right: # Step 5: Add right child to queue if exists
queue.append(node.right)
level_order(root) # Output: 1 2 3 4 5 6
🔹 Queue: [2, 3]
🔹 Queue: [3, 4, 5]
🔹 Queue: [4, 5, 6]
🚀 Traversal Complete!
📌 Real-Life Example:
The first person in the queue gets served first, just like level order traversal.
✅ Interactive Activity:
def height(root):
if not root:
return 0
📌 Definition:
The diameter of a binary tree is the longest path between any two nodes in the tree.
This path may or may not pass through the root.
📌 Formula:
Diameter = Max(Diameter of Left Subtree, Diameter of Right Subtree, Longest Path through Root)
def diameter_of_binary_tree(root): # We'll use a list to store the maximum diameter found
max_diameter = [0]
def height(node):
if not node:
return 0
left_height = height(node.left)
right_height = height(node.right)
return max_diameter[0]
1. Height Calculation:
o For each node, calculate the heights of its left and right subtrees.
o Example:
Copy
/\
2 3
/\
4 5
2. Diameter Update:
3. Global Maximum:
4. Final Result:
Key Features
Example Walkthrough
Copy
/\
2 3
/\
4 5
1. At Node 4 (Leaf):
2. At Node 5 (Leaf):
o Height = 1
3. At Node 2:
o Diameter = 1 + 1 = 2 (path: 4 → 2 → 5)
4. At Node 3 (Leaf):
o Height = 1
5. At Root (1):
o Diameter = 2 + 1 = 3 (path: 4 → 2 → 1 → 3)
The diameter is always the sum of the heights of the left and right subtrees of some node.
Here's a **clear, interactive 1-hour lesson plan** to teach counting leaf nodes and checking identical
trees, with simple code examples and hands-on activities:
---
**Interactive Demo**:
```
10
/ \
5 20
/\
3 7
```
### **Algorithm**
def count_leaves(root):
if not root:
return 0
return 1
**Live Walkthrough**:
- Leaves at 3, 7, 20 → Total = 3.
**Student Activity**:
```
/\
B C
/\
D E
```
**Interactive Demo**:
**Tree 1**:
```
1 Tree 2: 1
/\ /\
2 3 2 3
```
### **Algorithm**
```python
return True
return False
are_identical(root1.right, root2.right))
```
**Live Walkthrough**:
**Student Challenge**:
**Tree A**:
```
10 Tree B: 10
/ \ / \
5 20 5 20
```
**Answer**: Yes!
---
## **Wrap-Up (5 mins)**
**Key Takeaways**:
**Exit Ticket**:
```
/\
6 10
/ /\
5 9 11
```
1 1
/\ /\
2 3 2 3
/ \
4 4
```
---
- **Common Pitfalls**: