Data Structures: Binary Trees

Download Report

Transcript Data Structures: Binary Trees

Data Structures:
Binary Trees
CMSC 11500
Introduction to Computer Programming
October 28, 2002
Roadmap
• Recap: Family trees
• Generalizing: Binary trees
– Data definition
– Template
• Functions on Binary Trees
– Contains?
– Map-tree
– Fringe
• Summary
Family 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
Binary Trees
• More general form
– Nodes with two self-references
– Family trees -> self-refs= mother, father
• Data definition:
– (define-struct bt (val left right))
• Where val:number, left, right are binary-tree
– Binary-tree is:
• #f, or
• (make-bt val left right)
Binary 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))
Binary Tree Graphic
123
12
1
3
2
Binary 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))….))))))
Functions 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
Contains?
• Contract: binary-tree -> boolean
• Purpose: To determine if a given value is
in the tree
Contains?
(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))))
Map-tree
• Analogous to map for flat lists
• Applies some function to every element
• Contract:map-tree
– (number->number) binary-tree -> binary-tree
• Purpose:
– To apply function to every element of tree
Map-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)))))
Using Map-tree
• Square-tree:
– Contract: square-tree: binary-tree -> binary-tree
– Purpose: Square all numbers in tree
• Double-tree:
– Contract: double-tree: binary-tree -> binary-tree
– Purpose: Double all numbers in tree
Using Map-tree
(define (square-tree abt)
(map-tree square abt))
(define (double-tree abt)
(map-tree (lambda (x) (+ x x)) abt))
Next Time
• Binary Search Trees
– Invariants
– Efficient set implementation