Lecture 14
Trees!
Tree structures (root at the bottom)
Tree structures (root at the top)
Tree structures
File systems are trees
root
a
b
d
e
f
g
c
The DNS is a tree
root
edu
com
northwestern
berkeley
cnn
amazon
gov
it
cs
Data flow diagrams are (often) trees
Expressions are trees
(+ a
(- b)
(* c d)))
( )
+
a
( )
( )
-
b
*
c
d
Type hierarchies are trees
object
number
integer
float
procedure
posn
color
picture
string
boolean
exception
contract-violation
arity-mismatch
Even English sentences can be thought of as trees
Relationships between nodes
Relationships between nodes
Kinds of nodes
Kinds of nodes
Storing information in trees
( )
a
b
( )
( )
c
d
e
( )
f
( )
g
Trees are recursive
…
Representing�binary trees
Important: this is a somewhat different binary tree representation than the ones used in the tutorial and assignment; there are lots of ways to represent trees!
Example: binary trees
Example: binary trees
(define-struct binary-tree (data left right))
Example: binary trees
So the following are all valid binary trees:
(make-binary-tree 1 empty empty)
empty) ; by (a), (b) and rule 2
(make-binary-tree 1 empty empty)
(make-binary-tree 0 empty empty)) ; by (a), (b) and rule 2
(make-binary-tree 1
empty
(make-binary-tree 1 empty empty))
(make-binary-tree 1 empty empty)) ; by (a), (b) and rule 2
Tree Diagrams to Check Your Understanding
Writing a recursion
(define-struct binary-tree (data left right))
Example: Counting the nodes in a tree
(define (node-count tree)
(if (empty? tree)
0
(+ 1
(node-count (binary-tree-left tree))
(node-count (binary-tree-right tree)))))
More general trees
Another tree example
(define-struct tree (data child-list))
Examples
Tree Diagrams to Check Your Understanding
Counting the nodes in the new type of tree
(define (new-count-nodes tree)� (+ 1� (foldl + 0� (map new-count-nodes� (tree-child-list tree)))))
Or just:
(define (new-count-nodes tree)� (foldl + 1� (map new-count-nodes� (tree-child-list tree))))
Counting the nodes in the tree
(define (new-count-nodes tree)� (+ 1� (foldl + 0� (map new-count-nodes� (tree-child-list tree)))))
Nope!
Let’s run it on a leaf, using the substitution model:
(new-count-nodes (make-tree 1 '()))
Counting the nodes in the tree
(define (new-count-nodes tree)� (+ 1� (foldl + 0� (map new-count-nodes� (tree-child-list tree)))))