Title: Tree Data Structures: Family Trees
1Tree Data StructuresFamily Trees
- CMSC 11500
- Introduction to Computer Programming
- October 25, 2002
2Roadmap
- Recap Family trees
- Data definition Structures of structures
- Traversing tree data structures
- Collecting information from subtrees
- Recursive data, recursive traversal
- All-blue-eyed-ancestors
- Count-ancestors
- how-deep
- Summary
3(No Transcript)
4Data Definition
- A family-tree is
- unknown, or
- (make-ft name eye-color mother father)
- where name, eye-color are symbols mother,father
are family-tree - (define-struct ft (name eye-color mother father)
- (make-ft Granny Blue unknown unknown)
- (make-ft John Brown
- (make-ft Mom Green () ())..)
5Things to do with Family Trees
- Find ancestor(s) with certain traits
- e.g. eye-color, born before some date
- Find all traits for all relatives
- Compute relations between individuals
- Determine if they are related by blood
6All-blue-eyed-ancestors
- Get all ancestors (not just first)
- Contract a-b-e-a family-tree -gt (listof symbol)
- Purpose Find all blue-eyed-ancestors
- Helper append
- (append (a b c) (a b c)) -gt (a b c a b c)
- (define (append list1 list2)
- (cond ((null? list1) list2)
- (else (cons (car list1) (append (cdr
list1) list2)))
7All-blue-eyed-ancestors
(define (a-b-e-a aft) (cond
((eq? unknown aft) ())
((ft? aft)
(if (eq? (ft-eye-color aft) blue)
(cons (ft-name aft)
(append (a-b-e-a (ft-mother aft))
(a-b-e-a (ft-father aft))))
(append (a-b-e-a (ft-mother aft))
(a-b-e-a (ft-father aft))))))))
8All-blue-eyed-ancestors
(define (a-b-e-a aft) (cond
((eq? unknown aft) ())
(else (let ((in-parents
(append (a-b-e-a (ft-mother aft))
(a-b-e-a (ft-father aft)))))
(if (eq? (ft-eye-color aft) blue)
(cons (ft-name aft) in-parents) in-parents))))))
9Count-Ancestors
- Contract family-tree -gt number
- Purpose To compute number of ancestors of
family-tree node
10Count-ancestors
(define (count-ancestors aft) (cond
((eq? unknown aft) 0)
((ft? aft)
( 1
(count-ancestors (ft-mother aft))
(count-ancestors (ft-father aft))))))
11Count-ancestors
(define (count-ancestors aft)
(count-ancestors-iter aft 0))
(define (count-ancestors-iter aft anc-count)
(cond
((eq? unknown aft) anc-count)
((ft? aft)
(
(count-ancestors-iter (ft-mother aft) (
anc-count 1)) (count-ancestors-iter (ft-father
aft) ( anc-count 1))))))
12How-deep
- Contract family-tree -gt number
- Purpose To compute depth to most remote ancestor
13How-deep
(define (how-deep aft) (cond
((eq? unknown aft) 0)
((ft? aft)
( 1 (max (how-deep (ft-mother aft)))
(how-deep (ft-father aft)))))
14Summary
- Family trees
- Tree-structured data
- Recursive data definition, recursive traversal
- recursive calls self-referential parts in
d.d. - Different functions -gt different combiners
- Count-ancestors
- How-deep , max
- All-blue-eyed-ancestors append
15Next Time
- Data structures and analysis
- Binary trees
- Sets Binary search trees