Tree Data Structures Family Trees CMSC 11500 Introduction














- Slides: 14
Tree Data Structures: Family Trees CMSC 11500 Introduction to Computer Programming October 25, 2002
Roadmap • 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
Family Trees • Each child has: mother, father, & some attributes - e. g. birthdate, hair color, eye color
Data 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) • (make-ft ‘John ‘Brown – (make-ft ‘Mom ‘Green (…))…. . )
Things 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
All-blue-eyed-ancestors • • • Get all ancestors (not just first) Contract: a-b-e-a: family-tree -> (listof symbol) Purpose: Find all blue-eyed-ancestors Helper: “append” (append ‘(a b c)) -> ‘(a b c) (define (append list 1 list 2) – (cond ((null? list 1) list 2) – (else (cons (car list 1) (append (cdr list 1) list 2)))
All-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))))))))
All-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))))))
Count-Ancestors • Contract: family-tree -> number • Purpose: To compute number of ancestors of family-tree node
Count-ancestors (define (count-ancestors aft) (cond ((eq? ‘unknown aft) 0) ((ft? aft) (+ 1 (count-ancestors (ft-mother aft)) (count-ancestors (ft-father aft))))))
How-deep • Contract: family-tree -> number • Purpose: To compute depth to most remote ancestor
How-deep (define (how-deep aft) (cond ((eq? ‘unknown aft) 0) ((ft? aft) (+ 1 (max (how-deep (ft-mother aft))) (how-deep (ft-father aft)))))
Summary • Family trees: – Tree-structured data • Recursive data definition, recursive traversal • # recursive calls = # self-referential parts in d. d. • Different functions -> different combiners – Count-ancestors: + – How-deep: +, max – All-blue-eyed-ancestors: append
Next Time • Data structures and analysis – Binary trees – Sets: Binary search trees