Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Certified Racket AI Expert ยท Lesson 6 of 8

Module Five

๐Ÿ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
6
Module 5 ยท Racket AI Specialist โ€“ Recursion & Trees

๐ŸŒณ Module Five ยท Recursion on Trees & Advanced Data Processing

Certified Racket AI Specialist ยท Mastering Hierarchies

๐Ÿ“– Module Introduction

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!

๐ŸŒฒ Fun fact: Decision trees are used in many real-world AI systems โ€” from healthcare to video games!

๐ŸŽฏ Learning Objectives

After this module, you will be able to:

  • โœ”๏ธ Understand what a tree is and why it's important for AI.
  • โœ”๏ธ Traverse a tree in different ways (pre-order, in-order, post-order).
  • โœ”๏ธ Search for a value in a tree.
  • โœ”๏ธ Build a decision tree for a simple AI.
  • โœ”๏ธ Use recursion to process tree data.
  • โœ”๏ธ Combine trees with structures for more complex data.
  • โœ”๏ธ Understand how AI uses trees for decision-making.

๐Ÿ“š Warm-up Story ยท The Magical Maze

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
  

๐Ÿงฉ Main Lessons

Lesson 1 ยท Review: What is a Tree?

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
  
๐Ÿ“Œ Mini summary: A tree is a hierarchy with a root and branches.

Lesson 2 ยท Representing Trees in Racket

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.

๐Ÿ“Œ Mini summary: We use structs to build trees with a value and children list.

Lesson 3 ยท Pre-order Traversal

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))))))
  
๐Ÿ“Œ Mini summary: Pre-order: visit node, then children.

Lesson 4 ยท Post-order Traversal

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)))))
  
๐Ÿ“Œ Mini summary: Post-order: visit children, then node.

Lesson 5 ยท In-order Traversal (for binary trees)

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
  
๐Ÿ“Œ Mini summary: In-order: left, node, right (for binary trees).

Lesson 6 ยท Searching in a Tree

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))]))
  
๐Ÿ“Œ Mini summary: Search uses recursion to check every node.

Lesson 7 ยท Counting Nodes

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))))))
  
๐Ÿ“Œ Mini summary: Count all nodes by recursion.

Lesson 8 ยท Height of a 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))))))
  
๐Ÿ“Œ Mini summary: Height is the longest branch length.

Lesson 9 ยท Building a Decision 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.

๐Ÿ“Œ Mini summary: Decision trees ask questions to reach a decision.

Lesson 10 ยท Implementing a Decision Tree

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.

๐Ÿ“Œ Mini summary: We can implement decision trees with structures.

Lesson 11 ยท Evaluating a Decision Tree

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!

๐Ÿ“Œ Mini summary: Evaluating a decision tree asks questions and follows the path.

Lesson 12 ยท Putting It All Together โ€“ A Smart Chatbot

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!

๐Ÿ“Œ Mini summary: We combined everything to build an AI chatbot.

๐Ÿ“– Key Vocabulary

  • Tree: A structure with a root and branches.
  • Node: An element in a tree.
  • Leaf: A node with no children.
  • Traversal: Visiting every node in a tree.
  • Pre-order: Node, then children.
  • Post-order: Children, then node.
  • In-order: Left, node, right.
  • Decision tree: A tree used for making decisions.

๐Ÿง  Important Concepts

  • Recursion is key: Trees are processed recursively.
  • Order matters: Different traversals give different results.
  • Decision trees are AI: They are used in many AI systems.
  • Composition: Trees can be combined with structs.

๐Ÿ“˜ Step-by-Step Explanations

How to traverse a tree:

  1. Define the tree using structs or lists.
  2. Write a recursive function that handles a node.
  3. For pre-order: process node, then process each child.
  4. For post-order: process each child, then process node.
  5. For in-order (binary): process left, node, right.

๐ŸŒ Real-life Examples

  • Decision trees in medicine: diagnose illness.
  • Decision trees in banking: approve loans.
  • File systems: folders and subfolders.

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Market decisions: which market to go to based on price and distance.
  • School placement: which class a student should be in.
  • Village governance: decision tree for conflict resolution.

๐ŸŽˆ Fun Examples

  • What game to play: based on number of players.
  • What to watch: based on mood.
  • Which pet to get: based on house size.

๐Ÿ  Everyday Examples

  • What to wear: based on weather.
  • What to eat: based on hunger.
  • Which route to take: based on traffic.

๐Ÿง‘โ€๐Ÿซ Teacher Notes

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.

๐Ÿ‘ช Parent Tips

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.

๐ŸŒŸ Interesting Facts

  • Decision trees are used in Google's search algorithm.
  • The first decision tree was developed in the 1960s.
  • AI can learn decision trees automatically from data.

๐Ÿค” Did You Know?

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!

๐Ÿงพ Remember This

  • Trees have a root and branches.
  • Traversal visits every node.
  • Pre-order: node first.
  • Post-order: node last.
  • Decision trees help AI make decisions.

โš ๏ธ Common Mistakes

  • Forgetting the base case in recursive traversal.
  • Not handling empty children lists.
  • Confusing pre-order and post-order.
  • Not using empty? to check for no children.

โœ… Best Practices

  • Use structs to represent tree nodes.
  • Always write the base case first.
  • Use map and fold for child processing.
  • Test with small trees first.

๐Ÿ“Š ASCII Illustrations

   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
  

๐Ÿ“‹ Comparison Table

TraversalOrderUse
Pre-orderNode, childrenCopying trees
Post-orderChildren, nodeCalculating totals
In-orderLeft, node, rightSorted output

๐Ÿ“Œ End-of-Module Summary

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!

โ“ Frequently Asked Questions (10)

  1. What is a tree? โ€” A structure with a root and branches.
  2. What is a leaf? โ€” A node with no children.
  3. What is pre-order traversal? โ€” Visit node first, then children.
  4. What is post-order traversal? โ€” Visit children first, then node.
  5. What is a decision tree? โ€” A tree that helps make decisions.
  6. How do you search a tree? โ€” Traverse it and check each node.
  7. What is the height of a tree? โ€” The longest path from root to leaf.
  8. Why are trees important for AI? โ€” They are used for decision-making.
  9. Can a tree have more than two children? โ€” Yes, a general tree can.
  10. What is a binary tree? โ€” A tree where each node has at most two children.

๐Ÿ“ Review Questions (15)

  1. What is a tree?
  2. What is a leaf in a tree?
  3. What is pre-order traversal?
  4. What is post-order traversal?
  5. What is in-order traversal?
  6. How do you search for a value in a tree?
  7. What is a decision tree?
  8. Write a function to count the nodes in a tree.
  9. Write a function to calculate the height of a tree.
  10. How do you represent a tree in Racket?
  11. What is the difference between pre-order and post-order?
  12. Why is recursion useful for trees?
  13. Give an example of a decision tree in real life.
  14. Can a tree have zero nodes?
  15. What is the root of a tree?

โœ๏ธ Fill-in-the-Blank

  1. A ______ has a root and branches.
  2. A node with no children is called a ______.
  3. ______ traversal visits the node first, then children.
  4. ______ traversal visits children first, then node.
  5. A ______ tree helps make decisions.

โœ… True or False

  1. Pre-order visits children first. (False)
  2. Post-order visits node last. (True)
  3. A leaf has no children. (True)
  4. In-order is only for binary trees. (True)
  5. Decision trees are not used in AI. (False)

๐Ÿ”˜ Multiple Choice (15)

  1. What is a tree? A) root + branches B) list C) alist D) struct โ†’ A
  2. What is a leaf? A) node with no children B) root C) child D) branch โ†’ A
  3. Pre-order visits in what order? A) node, children B) children, node C) left, node, right D) right, node, left โ†’ A
  4. Post-order visits in what order? A) children, node B) node, children C) left, node, right D) right, node, left โ†’ A
  5. In-order visits in what order (for binary)? A) left, node, right B) node, left, right C) right, node, left D) children, node โ†’ A
  6. What is a decision tree? A) helps make decisions B) stores numbers C) sorts lists D) counts nodes โ†’ A
  7. How do you search a tree? A) traverse it B) use assoc C) use map D) use filter โ†’ A
  8. What is the height of a tree? A) longest path B) number of nodes C) number of leaves D) root value โ†’ A
  9. What is recursion? A) function calls itself B) loop C) if statement D) struct โ†’ A
  10. Can a tree have more than two children? A) yes B) no C) only two D) only one โ†’ A
  11. What is a binary tree? A) at most two children B) exactly two children C) only leaves D) no root โ†’ A
  12. Which traversal is used for copying trees? A) pre-order B) post-order C) in-order D) random โ†’ A
  13. Which traversal is used for evaluating expressions? A) post-order B) pre-order C) in-order D) none โ†’ A
  14. What does (node-value tree) return? A) the value of the node B) the children C) the root D) the leaf โ†’ A
  15. Why are trees important? A) organise data B) slow down programs C) delete data D) confuse programmers โ†’ A

๐Ÿ”— Matching

TermMatch
1. Pre-orderA. children first
2. Post-orderB. node first
3. LeafC. no children

Answers: 1-B, 2-A, 3-C

๐Ÿ“ Short Answer

  1. Explain the difference between pre-order and post-order.
  2. What is a decision tree and why is it useful?
  3. Write a function that returns the sum of all values in a tree.

๐Ÿ“– Scenario-based Exercises

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.

๐Ÿ‘ฅ Group Activity

Each group designs a decision tree for choosing a vacation destination. Questions: budget, beach or mountains, etc.

๐Ÿง‘โ€๐Ÿ’ป Individual Activity

Write a function that counts the number of leaves in a tree.

๐Ÿ’ฌ Classroom Discussion Questions

  • How is a decision tree like a flowchart?
  • Why are trees better than lists for some data?
  • What real-world problems can be solved with decision trees?

๐Ÿ› ๏ธ Mini Project

Build a decision tree that helps choose a pet. Questions: Do you have a yard? Do you like walking? etc.

๐Ÿ“‹ Practical Assignment

Implement a decision tree for a restaurant recommendation based on cuisine preference and budget.

๐Ÿ† Challenge Exercise

Write a function that flattens a tree into a list using pre-order traversal.

๐Ÿ”‘ Quiz Answers

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.

๐ŸŽ Key Takeaways

  • Trees are hierarchical structures.
  • Traversal visits every node in a specific order.
  • Decision trees are a core AI tool.
  • Recursion is natural for trees.
  • You can build interactive AI with decision trees.

๐Ÿš€ Preparation for the Next Module

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! ๐ŸŽ‰

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (โ‚ฆ2,000 or 20,000 coins), and get a verified certificate with your name on it.

๐ŸŽ“ Sign Up to Get Certified
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
โ†’