Title: Data Structures: Binary Trees
1Data StructuresBinary Trees
- CMSC 11500
- Introduction to Computer Programming
- October 28, 2002
2Roadmap
- Recap Family trees
- Generalizing Binary trees
- Data definition
- Template
- Functions on Binary Trees
- Contains?
- Map-tree
- Fringe
- Summary
3Family Trees
- Data definition
- (define-stuct ft (name eye-color mother father))
- Where name, eye-color symbols, mother, father
are - Family-tree is
- 1) unknown, or
- 2) (make-ft name eye-color mother father)
- (define nana (make-ft alice blue unknown
unknown)) - (define ma (make-ft anna brown nana pap))
- Functions
- Blue-eyed ancestor, all-blue-eyed-ancestors,
how-deep
4Binary Trees
- More general form
- Nodes with two self-references
- Family trees -gt self-refs mother, father
- Data definition
- (define-struct bt (val left right))
- Where valnumber, left, right are binary-tree
- Binary-tree is
- f, or
- (make-bt val left right)
5Binary Tree Examples
- Vocabulary
- If bt-left bt-right both f, leaf node
- If not bt-left or bt-right of other node, root
- (define leaf1 (make-bt 1 f f))
- (define leaf2 (make-bt 2 f f))
- (define leaf3 (make-bt 3 f f))
- (define mid12 (make-bt 12 leaf1 leaf2))
- (define root (make-bt 123 mid12 leaf3))
6Binary Tree Graphic
123
12
3
1
2
7Binary Tree Template
- Questions
- How many conditions? , How many parts?, How many
what self-references? - (define (fn-for-btree abt)
- (cond ((eq? abt f) .)
- ((bt? abt)
- (cond ((eq? (bt-val abt) ) .)
- . (fn-for-btree (bt-left
abt)) - . (fn-for-btree (bt-right
abt)).))))))
8Functions on Binary Trees
- Is x in the tree?
- Contains?
- Do something to every element in the tree
- map-tree
- Find the nodes with no successors
- fringe
9Contains?
- Contract binary-tree -gt boolean
- Purpose To determine if a given value is in the
tree
10Contains?
(define (contains? testnum abt)
(cond ((eq? abt f) f)
((bt? abt)
(cond ((eq? (bt-val abt) testnum) t)
(else (or (contains? testnum (bt-left abt))
(contains? testnum (bt-right abt))))))))
11Map-tree
- Analogous to map for flat lists
- Applies some function to every element
- Contractmap-tree
- (number-gtnumber) binary-tree -gt binary-tree
- Purpose
- To apply function to every element of tree
12Map-tree
(define (map-tree func abt) (cond ((eq? abt f)
f) ((bt? abt) (make-bt (func (bt-val
abt)) (map-tree func (bt-left
abt)) (map-tree func (bt-right abt)))))
13Using Map-tree
- Square-tree
- Contract square-tree binary-tree -gt binary-tree
- Purpose Square all numbers in tree
- Double-tree
- Contract double-tree binary-tree -gt binary-tree
- Purpose Double all numbers in tree
14Using Map-tree
(define (square-tree abt) (map-tree square
abt)) (define (double-tree abt) (map-tree
(lambda (x) ( x x)) abt))
15Next Time
- Binary Search Trees
- Invariants
- Efficient set implementation