Skip to content
Snippets Groups Projects
Commit eda423c8 authored by Romain Vuillemot's avatar Romain Vuillemot
Browse files

trees material

parent 8371e1e4
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:91c9c0b9 tags:
NAME:
%% Cell type:markdown id:3bae696a-8e88-4a34-89f6-a0f4d9551e9b tags:
# Binary trees
%% Cell type:markdown id:7c7461c1-fe15-405b-a2c9-709e6f9c3743 tags:
---
%% Cell type:markdown id:a2428808-27d5-4d42-84b8-01632b1271dd tags:
## Exercise 1: Write the code for this binary tree
_Use a `dict()` data structure for the list of nodes._
%% Cell type:code id:83b91119-09f7-4cba-a87b-19fc4a793e91 tags:
``` python
from graphviz import Digraph
dot = Digraph()
dot.node_attr['shape'] = 'circle'
dot.node('0', label='0') # Root
dot.node('1')
dot.node('2')
dot.node('3')
dot.node('4')
dot.node('5')
dot.edge('0', '1')
dot.edge('1', '4')
dot.edge('1', '5')
dot.edge('0', '2', color='red')
dot.edge('2', '3', color='red')
dot # Render the graph
```
%% Cell type:markdown id:1fca57f5-4b3c-4ad8-a4c0-9d1de647abf9 tags:
_Use a `Dict` data structure for nodes and also for edges edges._
%% Cell type:code id:fa1bce0f-7b06-4d20-8a1b-990bcd03bda9 tags:
``` python
# YOUR CODE HERE
raise NotImplementedError()
```
%% Cell type:markdown id:cb16382b-e00d-498a-bab2-0b251f93d147 tags:
_Use a `Tuple` data structure for nodes and edges._
%% Cell type:code id:a4cbc1d4-5adc-4cda-9c2a-24101bd1bed9 tags:
``` python
# YOUR CODE HERE
raise NotImplementedError()
```
%% Cell type:markdown id:fb0e9336-603c-49c4-9617-9ccecdbf7156 tags:
# Exercise: binary search tree
_We assume we have a binary search tree (BST). Its main property is that for every node, the value of the left children is less than the value of the right children._
%% Cell type:code id:02513514-0e1b-4c0d-a5fd-ac6b571231b7 tags:
``` python
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def __str__(self):
return str(self.value)
```
%% Cell type:markdown id:055d2cea-4e45-402d-baf8-e50939c94132 tags:
Write an `insert` function inserts a value in a tree so it preserves the BST property.
%% Cell type:code id:6492983d-054c-4488-b8ff-57b3878f5b7e tags:
``` python
def insert(root, value):
# YOUR CODE HERE
raise NotImplementedError()
```
%% Cell type:code id:7c2a2f74-a8b8-4cd6-a881-9181efdb7a64 tags:
``` python
a = Node(2)
insert(a, 3)
insert(a, 4)
insert(a, 1)
```
%% Cell type:code id:10b6d8de-fb38-41e3-92b9-957f04a6f1e4 tags:
``` python
visualize_oop(a)
```
%% Cell type:markdown id:07ca3602-96fd-43d7-b7ac-54f92124a11d tags:
# Exercice: calculate the height using OOP
%% Cell type:code id:2e65ec3d-8e90-4e25-befb-d779713fa3f2 tags:
``` python
class Node:
def __init__(self, value, l = None, r = None):
self.value = value
self.left = l
self.right = r
```
%% Cell type:markdown id:3bd05d7e-7e0c-4042-9aac-616960849de9 tags:
In a recursive way:
%% Cell type:code id:c323b9af-98f6-45d6-9ee2-cffde39a2a16 tags:
``` python
def recursive_tree_height(node):
# YOUR CODE HERE
raise NotImplementedError()
```
%% Cell type:code id:9527fa59-87cf-4216-a7dc-ad0aa3330d4c tags:
``` python
assert recursive_tree_height(Node(2)) == 0
assert recursive_tree_height(Node(2, Node(3))) == 1
assert recursive_tree_height(Node(2, Node(3, Node(4)))) == 2
```
%% Cell type:markdown id:7b46712d-472b-4997-90b4-acda29a17fb9 tags:
In an interative way:
%% Cell type:code id:6cd2bdcf-d4ad-4103-88ed-ced3fb45f4e8 tags:
``` python
def iterative_tree_height(root):
# YOUR CODE HERE
raise NotImplementedError()
```
%% Cell type:code id:dac217fa-c9db-46ca-91a3-a834c3d0aa38 tags:
``` python
assert iterative_tree_height(Node(2)) == 0
assert iterative_tree_height(Node(2, Node(3))) == 1
assert iterative_tree_height(Node(2, Node(3, Node(4)))) == 2
```
%% Cell type:markdown id:5e50ca4a-6aaf-4620-924a-eb6d8a00efaf tags:
# Utils
%% Cell type:code id:0c319da6-cee4-447f-b178-0ed04da67273 tags:
``` python
from graphviz import Digraph
from IPython.display import display
class Node:
def __init__(self, value, l = None, r = None):
self.value = value
self.left = l
self.right = r
def visualize_oop(root):
def build(node, dot=None):
if dot is None:
dot = graphviz.Digraph(format='png')
if node is not None:
dot.node(str(node.value))
if node.left is not None:
dot.edge(str(node.value), str(node.left.value))
build(node.left, dot)
if node.right is not None:
dot.edge(str(node.value), str(node.right.value))
build(node.right, dot)
return dot
return build(root)
```
%% Cell type:code id:b5866309-ceba-4d71-a2e0-5df6e5e18b25 tags:
``` python
visualize_oop(Node(3, Node(2)))
```
File added
File added
File added
This diff is collapsed.
%% Cell type:markdown id:a4973a08 tags:
# UE5 Fundamentals of Algorithms
## Lecture 9: Binary trees traversals
### Ecole Centrale de Lyon, Bachelor of Science in Data Science for Responsible Business
#### Romain Vuillemot
<center><img src="figures/Logo_ECL.png" style="width:300px"></center>
%% Cell type:markdown id:01f6da4e tags:
---
%% Cell type:markdown id:6efad77c tags:
## Outline
- Traversal methods
- Depth first
- Breadth first
%% Cell type:markdown id:9fc3736a tags:
## Traversal methods
> Methodes to explore and process all the nodes in a binary tree
- Because Trees are non-linear, there are multiple possible paths
%% Cell type:markdown id:7946fdbc tags:
## Two main traversal strategies:
<img src="figures/arbre-largeur-hauteur.png" style="width: 400px">
1. **Depth-First Traversal (DFS):**
- visiting a node (sarting with the root)
- then recursively traversing as deep as possible
- then explore another branch.
2. **Breadth-First Traversal (BFS):**
- visiting a node (sarting with the root)
- explore all its neighbors (children)
- then mode move to the children.
%% Cell type:markdown id:66c57c10 tags:
## Depth-first
**Pseudo-code for Depth-First Traversal:**
1. Place the source node in the **stack**.
2. Remove the node from the top of the stack for processing.
3. Add all unexplored neighbors to the stack (at the top).
4. If the stack is not empty, go back to step 2.
%% Cell type:code id:41790c1d tags:
``` python
def dfs(graph, start):
stack = [start]
while stack:
vertex = stack.pop()
print(vertex) # traitement
stack.extend(graph[vertex])
graph = {'A': set(['B', 'C']),
'B': set(['D', 'E', 'F']),
'C': set([]),
'D': set([]),
'E': set([]),
'F': set([])
}
dfs(graph, 'A') # A B D F E C
```
%% Output
A
B
D
E
F
C
%% Cell type:markdown id:da082c74 tags:
## Depth-first traversal: pre-order, in-order, and post-order.
For **depth-first traversal**, there are different types of processing: *pre-order*, *in-order*, and *post-order*.
- R = Root
- D = Right subtree
- G = Left subtree
There are three (main) types of traversal, observing the position of R:
- **Pre-order**: R G D
- **In-order**: G R D
- **Post-order**: G D R
%% Cell type:markdown id:f0c20b5a tags:
## Depth-first traversal: pre-order, in-order, and post-order.
For **depth-first traversal**, there are different types of processing: *pre-order*, *post-order*, and *in-order*.
```python
def Preorder(R):
if not empty(R):
process(R) # Root
Preorder(left(R)) # Left
Preorder(right(R)) # Right
def Inorder(R):
if not empty(R):
Inorder(left(R)) # Left
process(R) # Root
Inorder(right(R)) # Right
def Postorder(R):
if not empty(R):
Postorder(left(R)) # Left
Postorder(right(R)) # Right
process(R) # Rooot
%% Cell type:markdown id:6d493663 tags:
## Depth-first traversal: pre-order
_Iterative implementation._
%% Cell type:code id:b0d812d9 tags:
``` python
def iterative_inorder_traversal(root):
stack = []
current = root
while current is not None or stack:
while current is not None:
stack.append(current)
current = current.left
current = stack.pop()
print(current.value)
current = current.right
```
%% Cell type:markdown id:f368960e tags:
## Depth-first traversal: pre-order
_Recursive implementation._
%% Cell type:code id:552dc46b tags:
``` python
TT = {"dog": ["little", "very"],
"little": ["the"],
"the": [],
"very": ["is", "cute"],
"is": [],
"cute": []
}
```
%% Cell type:code id:2cafcf1c tags:
``` python
def preorder(T, node):
if node is not None:
if len(T[node]) > 0:
preorder(T, T[node][0])
print(node)
if len(T[node]) > 1:
preorder(T, T[node][1])
```
%% Cell type:code id:8b8f5c52 tags:
``` python
preorder(TT, "dog")
```
%% Output
the
little
dog
is
very
cute
%% Cell type:code id:fbbb9408 tags:
``` python
def preorder_traversal(node):
if node is not None:
if node.left:
preorder_traversal(node.left)
print(node.value)
if node.right:
preorder_traversal(node.right)
root = Node("dog")
root.left = Node("little")
root.left.left = Node("the")
root.right = Node("very")
root.right.left = Node("is")
root.right.right = Node("cute")
preorder_traversal(root)
```
%% Output
the
little
dog
is
very
cute
%% Cell type:code id:72f665f2 tags:
``` python
visualize_oop(root)
```
%% Output
<graphviz.graphs.Digraph at 0x1045bead0>
%% Cell type:markdown id:c88e5f58 tags:
## Breadth-first traversal
_Visit all the nodes in a tree or graph level by level._
```
1
/ \
2 3
/ \
4 5
```
%% Cell type:code id:73ceb6d8 tags:
``` python
def bfs_print(node):
if node is None:
return
queue = [node]
while queue:
current_node = queue.pop(0)
print(current_node.value, end=' ')
if current_node.left:
queue.append(current_node.left)
if current_node.right:
queue.append(current_node.right)
```
%% Cell type:code id:1e1a1f21 tags:
``` python
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
bfs_print(root)
```
%% Output
1 2 3 4 5
%% Cell type:markdown id:7ba7af33 tags:
## Utils
%% Cell type:code id:2dc5a89d tags:
``` python
import graphviz
from graphviz import Digraph
from IPython.display import display
```
%% Cell type:code id:7058a231 tags:
``` python
def visualize_oop(root):
def build(node, dot=None):
if dot is None:
dot = graphviz.Digraph(format='png')
if node is not None:
dot.node(str(node.value))
if node.left is not None:
dot.edge(str(node.value), str(node.left.value))
build(node.left, dot)
if node.right is not None:
dot.edge(str(node.value), str(node.right.value))
build(node.right, dot)
return dot
return build(root)
```
%% Cell type:code id:05b69326 tags:
``` python
```
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment