Add lesson 6: Trees and recursion
3 changed files with 49 additions and 0 deletions
lessons/06-trees-and-recursion/README.md ADDED
| @@ -0,0 +1,19 @@ | ||
| 1 | +# Lesson 6: Trees and recursion | |
| 2 | + | |
| 3 | +This lesson covers trees and recursion. You'll read a short explanation, try three small exercises and finish with a quiz. | |
| 4 | + | |
| 5 | +Full lesson: [https://glibcode.net/courses/algorithms/lessons/6](https://glibcode.net/courses/algorithms/lessons/6) | |
| 6 | + | |
| 7 | +## Files | |
| 8 | + | |
| 9 | +- `trees.py`: a binary tree, its depth and an in-order walk | |
| 10 | + | |
| 11 | +## Run it | |
| 12 | + | |
| 13 | +```sh | |
| 14 | +python3 trees.py | |
| 15 | +``` | |
| 16 | + | |
| 17 | +## Exercises | |
| 18 | + | |
| 19 | +See [exercises.md](exercises.md). Ask in the forum once you've tried. | |
lessons/06-trees-and-recursion/exercises.md ADDED
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Exercises: lesson 6 | |
| 2 | + | |
| 3 | +1. Look up one function or command the example uses in the official documentation. Note one option you didn't know. | |
| 4 | +2. Combine this lesson with the previous one: use something from both in a small program of your own. | |
| 5 | +3. Break the example on purpose: delete a bracket or misspell a name. Read the error message. Which line does it point to? | |
lessons/06-trees-and-recursion/trees.py ADDED
| @@ -0,0 +1,25 @@ | ||
| 1 | +from dataclasses import dataclass | |
| 2 | + | |
| 3 | + | |
| 4 | +@dataclass | |
| 5 | +class Node: | |
| 6 | + value: int | |
| 7 | + left: "Node | None" = None | |
| 8 | + right: "Node | None" = None | |
| 9 | + | |
| 10 | + | |
| 11 | +def depth(node): | |
| 12 | + if node is None: | |
| 13 | + return 0 | |
| 14 | + return 1 + max(depth(node.left), depth(node.right)) | |
| 15 | + | |
| 16 | + | |
| 17 | +def in_order(node): | |
| 18 | + if node: | |
| 19 | + yield from in_order(node.left) | |
| 20 | + yield node.value | |
| 21 | + yield from in_order(node.right) | |
| 22 | + | |
| 23 | + | |
| 24 | +root = Node(8, Node(3, Node(1), Node(6)), Node(10, right=Node(14))) | |
| 25 | +print(depth(root), list(in_order(root))) | |