Certified Racket AI Specialist ยท Mastering Hierarchies
Hello, clever thinker! ๐ In Module Four, we learned about data structures like structs, association lists, and trees. Now we will become masters of trees โ one of the most important structures in AI.
Think about how your family tree works: you start with your grandparents, then parents, then you, then your siblings. A computer can use this same idea to make decisions, organise data, and even play games!
In this module, we will learn how to walk through (traverse) trees, search for values in trees, and even build decision trees โ the same kind used in real AI systems to decide things like whether to give you a loan or diagnose an illness. By the end, you'll be able to build your own simple AI that makes decisions based on a tree!
After this module, you will be able to:
Imagine you are in a magical maze. At each junction, you can go left or right. Some paths lead to treasure, others lead to dead ends. You want to find all the treasure.
If you start at the entrance and explore every path, you are traversing the maze. You might decide to go left first, then right โ that's an order of traversal.
In programming, a tree is like that maze. Each node (junction) has branches (paths). We can write recursive functions to explore every node and find what we need.
Let's learn how to navigate these magical trees!
Magical Maze (Tree):
Entrance
/ \
Left Right
/ \ / \
L1 L2 R1 R2
Definition: A tree is a structure with a root (top) and branches (children). Each branch can have more branches. A node with no children is called a leaf.
Why important: Trees are everywhere in AI: decision trees, file systems, website menus, and more.
Simple explanation: Think of a family tree: grandparents at the top, then parents, then children. That's a tree.
Real-life: A company organogram: CEO โ managers โ employees.
School: A school system: Principal โ Head Teachers โ Class Teachers โ Students.
Home: A wardrobe: Clothes โ Tops โ Shirts.
Nigerian: Traditional title system: Oba โ Chiefs โ Village Heads โ People.
Illustration:
Root
/ \
NodeA NodeB
/ \ |
Leaf1 Leaf2 Leaf3
We can use structures to represent tree nodes. Each node has a value and a list of children.
(struct node (value children)) (define leaf1 (node 5 '())) (define leaf2 (node 7 '())) (define branch (node 3 (list leaf1 leaf2))) (define root (node 10 (list branch)))
This creates a tree: root 10 โ child 3 โ children 5 and 7.
Definition: Pre-order traversal visits the current node first, then each child.
Why important: Useful for copying a tree or saving its structure.
Simple explanation: Like a teacher calling out the class list: "Ade, then his children, then Bola..."
Real-life: Reading a book: start at chapter 1, then its sections.
School: Taking attendance: call the class captain, then their group members.
Home: Packing a suitcase: put big items first, then smaller ones.
Nigerian: Serving food: give the head of the family first, then others.
Illustration:
Pre-order: Root โ Left โ Right
Tree: 10
/ \
5 3
/ \ / \
2 7 4 6
Pre-order: 10, 5, 2, 7, 3, 4, 6
(define (pre-order tree)
(if (empty? (node-children tree))
(list (node-value tree))
(cons (node-value tree)
(foldr append '() (map pre-order (node-children tree))))))
Definition: Post-order visits all children first, then the node itself.
Why important: Used to calculate totals or evaluate expressions.
Simple explanation: Like cleaning a room: you clean the floor, then the table, then you leave.
Real-life: Eating a meal: you eat the vegetables, then the meat, then you finish.
School: Grading: you mark each student's work, then calculate the class average.
Home: Taking out trash: you empty all bins, then take the bag out.
Nigerian: Harvesting: you pick all the fruits, then take them to the market.
Illustration:
Post-order: Left โ Right โ Root
Tree: 10
/ \
5 3
/ \ / \
2 7 4 6
Post-order: 2, 7, 5, 4, 6, 3, 10
(define (post-order tree)
(if (empty? (node-children tree))
(list (node-value tree))
(append (foldr append '() (map post-order (node-children tree)))
(list (node-value tree)))))
Definition: In-order visits left child, then node, then right child (for binary trees).
Why important: This is used for sorted data โ like printing a sorted list.
Simple explanation: Like reading a dictionary: A, then B, then C...
Real-life: Organising files by date: oldest first, then newest.
School: Calling roll: start from A, go to Z.
Home: Sorting toys: put all red ones, then blue, then green.
Nigerian: Market prices: low to high.
Illustration:
In-order: Left โ Root โ Right
Tree: 10
/ \
5 3
/ \ / \
2 7 4 6
In-order: 2, 5, 7, 10, 4, 3, 6
We can search for a value in a tree by traversing it and checking each node.
(define (search tree target)
(cond
[(equal? (node-value tree) target) #t]
[(empty? (node-children tree)) #f]
[else (ormap (lambda (child) (search child target)) (node-children tree))]))
We can count how many nodes are in a tree by traversing it.
(define (count-nodes tree)
(if (empty? (node-children tree))
1
(+ 1 (foldl + 0 (map count-nodes (node-children tree))))))
The height of a tree is the longest path from root to a leaf.
(define (height tree)
(if (empty? (node-children tree))
1
(+ 1 (apply max (map height (node-children tree))))))
A decision tree is a tree where each node asks a question, and the branches are the answers. At the leaves, we get a decision.
Example: Should I play outside?
Decision Tree:
Is it sunny?
/ \
Yes No
/ \
Is it warm? Stay inside
/ \
Yes No
/ \
Play Stay in
We can build this in Racket using structs.
Let's implement a simple decision tree that decides what to wear.
(struct question (text yes no))
(struct answer (text))
(define decision-tree
(question "Is it raining?"
(question "Is it windy?"
(answer "Wear a jacket and umbrella")
(answer "Wear a jacket"))
(answer "Wear light clothes")))
We can write a function to evaluate the tree with user input.
Write a function that asks questions and returns the final answer.
(define (decide tree)
(cond
[(answer? tree) (answer-text tree)]
[(question? tree)
(display (question-text tree))
(newline)
(if (equal? (read-line) "yes")
(decide (question-yes tree))
(decide (question-no tree)))]))
This creates an interactive AI!
Let's build a simple chatbot that helps decide what to eat for lunch.
; Build the tree
(define food-tree
(question "Do you want something hot?"
(question "Do you want rice?"
(answer "Jollof rice")
(answer "Yam and egg"))
(question "Do you want something cold?"
(answer "Salad")
(answer "Fruit juice"))))
; Run (decide food-tree)
You just built a tiny AI assistant!
How to traverse a tree:
Use physical trees (draw on board). Use real decision-making scenarios. Encourage students to build decision trees for everyday choices. Emphasise that recursion is natural for trees.
Ask your child to draw a decision tree for a simple decision (like what to wear). Discuss how computers use these trees. Practice together by building a tree for a family decision.
Decision trees are so popular because they are easy to understand. You can draw them on a piece of paper and explain them to anyone!
empty? to check for no children.map and fold for child processing.Tree traversal order: Pre-order: Root โ Left โ Right In-order: Left โ Root โ Right Post-order: Left โ Right โ Root
Decision tree flow:
Start
|
V
Question 1
/ \
Yes No
| |
V V
Q2 Q3
| |
V V
Decision Decision
| Traversal | Order | Use |
|---|---|---|
| Pre-order | Node, children | Copying trees |
| Post-order | Children, node | Calculating totals |
| In-order | Left, node, right | Sorted output |
You've become a tree master! You can now traverse trees in different orders, search for values, count nodes, and even build decision trees โ the heart of many AI systems. You've built a simple chatbot that makes decisions. These skills are directly used in real AI applications. You're now ready to explore even more advanced AI topics!
| Term | Match |
|---|---|
| 1. Pre-order | A. children first |
| 2. Post-order | B. node first |
| 3. Leaf | C. no children |
Answers: 1-B, 2-A, 3-C
Scenario: You are building a system to recommend a movie based on age and interest. Design a decision tree for this.
Answer: Tree: Is age < 12? โ Cartoon; else โ Is it action? โ Action; else โ Comedy.
Each group designs a decision tree for choosing a vacation destination. Questions: budget, beach or mountains, etc.
Write a function that counts the number of leaves in a tree.
Build a decision tree that helps choose a pet. Questions: Do you have a yard? Do you like walking? etc.
Implement a decision tree for a restaurant recommendation based on cuisine preference and budget.
Write a function that flattens a tree into a list using pre-order traversal.
Multiple choice answers: 1-A, 2-A, 3-A, 4-A, 5-A, 6-A, 7-A, 8-A, 9-A, 10-A, 11-A, 12-A, 13-A, 14-A, 15-A.
In Module Six, we will explore Generative AI โ how computers can create new things like stories, pictures, and music. We'll use what we've learned about trees and recursion to build creative programs. Get ready to become an AI artist!
๐ You've completed Module Five ยท You are now a tree and decision-making expert! ๐