readings: topics - university of waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > tree...

99
Trees Readings: HtDP, sections 14, 15, 16. Topics: Introductory examples and terminology Binary trees Binary search trees Augmenting trees Binary expression trees General arithmetic expression trees Nested lists Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists 1/91 11: Trees CS 135

Upload: others

Post on 01-Jan-2021

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Trees

Readings: HtDP, sections 14, 15, 16.

Topics:

Introductory examples and terminology

Binary trees

Binary search trees

Augmenting trees

Binary expression trees

General arithmetic expression trees

Nested lists

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

1/91 11: Trees CS 135

Page 2: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Example: binary expression trees

The expression ((2 ∗ 6) + (5 ∗ 2))/(5− 3) can be represented as a tree:

/+ -

35* *

2562

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

2/91 11: Trees CS 135

Page 3: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Example: Phylogentic trees

This phylogentic treetracks the evolution ofCOVID-19 in the firstfour months of therecent pandemic.Image: nextstrain.org/ncov

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

3/91 11: Trees CS 135

Page 4: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Tree terminology (1/2)

nodesroot

edges

A tree is a set of nodes and edges where an edgeconnects two distinct nodes.A tree has three requirements:

One node is identified as the root.

Every node c other than the root is connected byan edge to some other node p. p is called theparent and c is called the child.

A tree is connected:for every node n other than the root,the parent of n orthe parent of the parent of n orthe parent of the parent ... of n will be the root.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

4/91 11: Trees CS 135

Page 5: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Tree terminology (2/2)

8

14labels

leaves

internal nodes

subtree

Other useful terms:

leaves: nodes with no children

internal nodes: nodes that have children

labels: data attached to a node

ancestors of node n: n itself, the parent of n, theparent of the parent of n, etc. up to the root

descendents of n: all the nodes that have n asan ancestor

subtree rooted at n: n and all of its descendants

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

5/91 11: Trees CS 135

Page 6: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Characteristics of trees

Number of children of internalnodes:

exactly twoat most twoany number

Labels:on all nodesjust on leaves

Order of children (matters or not)

Tree structure (from data or forconvenience)

/+ -

35* *

2562

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

6/91 11: Trees CS 135

Page 7: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Binary trees

A binary tree is a tree with at most two children for each node.

Binary trees are a fundamental part of computer science, independent of whatlanguage you use.

Binary arithmetic expression trees and evolution trees are both examples of binarytrees.

We’ll start with the simplest possible binary tree. It could be used to store a set ofnatural numbers.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

7/91 11: Trees CS 135

Page 8: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Drawing binary trees

5

71

146

51 7

146

Note: We will consistently use Nats in our binary trees, but we could use symbols,strings, structures, ...

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

8/91 11: Trees CS 135

Page 9: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Binary tree data definition

(define-struct node (key left right));; A Node is a (make-node Nat BT BT)

;; A binary tree (BT) is one of:;; * empty;; * Node

The node’s label is called “key” in anticipation of using binary trees to implementdictionaries.

What is the template?

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

9/91 11: Trees CS 135

Page 10: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Aside: Tips for building templates

Follow the data definition. For each part of the data definition, if it

is a defined data type, apply that type’s template.

says “one of” or is mixed data, include a cond to distinguish the cases.

is compound data (a structure), extract each of the fields, in order.

is a list, extract the first and rest of the list.

Add elipses (. . . ) around each of the above.

Apply the above recursively.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

10/91 11: Trees CS 135

Page 11: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Binary tree template

;; bt-template: BT → Any(define (bt-template t)

Check your template! How did you do?

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

11/91 11: Trees CS 135

Page 12: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Example: sum-keys

;; (sum-keys bt) sums the keys in the binary tree bt.;; Examples(check-expect (sum-keys empty) 0)(check-expect (sum-keys (make-node 10 empty empty)) 10)(check-expect (sum-keys (make-node 10

(make-node 5 empty empty)empty)) 15)

;; sum-keys: BT → Nat(define (sum-keys bt)

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

12/91 11: Trees CS 135

Page 13: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Example: count-nodes

(define test-tree (make-node 5 (make-node 1 ...(make-node 1 ...))))

;; (count-nodes tree k) counts the number of nodes in the tree that;; have a key equal to k.(check-expect (count-nodes empty 5) 0)(check-expect (count-nodes test-tree 1) 3)

;; count-nodes: BT Nat → Nat(define (count-nodes tree k)(cond [(empty? tree) 0]

[else (+ (cond [(= k (node-key tree)) 1][else 0])

(count-nodes (node-left tree) k)(count-nodes (node-right tree) k))]))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

13/91 11: Trees CS 135

51

6

1

6 13 3

4

Page 14: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Example: Increment keys

;; (increment tree) adds 1 to each key in the tree.;; increment: BT → BT(define (increment tree)(cond[(empty? tree) empty][else (make-node (add1 (node-key tree))

(increment (node-left tree))(increment (node-right tree)))]))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

14/91 11: Trees CS 135

Page 15: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Exercise 1

Write (count-leaves t) which consumes a binary tree and produces thenumber of leaf nodes.

Write (count-evens t) which consumes a binary tree and produces thenumber of nodes with an even key.

Write (reverse-tree t) which consumes a binary tree and produces a newtree that has the same keys as t but every node has the left and rightsubtrees reversed (the left subtree becomes the right; the right subtreebecomes the left).

Page 16: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Searching binary trees

We are now ready to search our binary tree for a given key. It will produce true ifthe key is in the tree and false otherwise.

Our strategy:

See if the root node contains the key we’re looking for. If so, produce true.

Otherwise, recursively search in the left subtree and in the right subtree. Ifeither recursive search finds the key, produce true. Otherwise, produce false.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

15/91 11: Trees CS 135

Page 17: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Searching binary trees

Now we can fill in our BT template to write our search function:

;; (search k tree) produces true if k is in tree; false otherwise.;; search: Nat BT → Bool(define (search-bt k tree)(cond [(empty? tree) false]

[(= k (node-key tree)) true][else (or (search-bt k (node-left tree))

(search-bt k (node-right tree)))]))

Is this more efficient than searching a list?

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

16/91 11: Trees CS 135

Page 18: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Exercise 2

Correct the contains? function, above. Keep to the spirit of the existing functionand use a Boolean expression with no helper functions.

Page 19: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Find the path to a key

Write a function, search-bt-path, thatsearches for an item in the tree. Asbefore, it will return false if the item isnot found. However, if it is foundsearch-bt-path will return a list of thesymbols 'left and 'right indicatingthe path from the root to the item.

If the tree contains a duplicate,produce the path to the left-most item.

63 10

32 45

9 5The path from 6 to 9 is'(right right left).

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

17/91 11: Trees CS 135

Page 20: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Find the path to a key

(define test-tree(make-node 6 (make-node 3 ...)

(make-node 10 ...)))

63 10

32 45

9 5(check-expect (search-bt-path-v1 0 empty) false)(check-expect (search-bt-path-v1 6 test-tree) empty)(check-expect (search-bt-path-v1 3 test-tree) '(left))(check-expect (search-bt-path-v1 9 test-tree) '(right right left))(check-expect (search-bt-path-v1 0 test-tree) false)

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

18/91 11: Trees CS 135

Page 21: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> search-bt-path

;; search-bt-path-v1: Nat BT → (anyof false (listof Sym))(define (search-bt-path-v1 k tree)(cond[(empty? tree) false][(= k (node-key tree)) '()][(list? (search-bt-path-v1 k (node-left tree)))(cons 'left (search-bt-path-v1 k (node-left tree)))][(list? (search-bt-path-v1 k (node-right tree)))(cons 'right (search-bt-path-v1 k (node-right tree)))][else false]))

Double calls to search-bt-path. Uggh!

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

19/91 11: Trees CS 135

Page 22: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Improved search-bt-path

;; search-bt-path-v2: Nat BT → (anyof false (listof Sym))(define (search-bt-path-v2 k tree)(cond[(empty? tree) false][(= k (node-key tree)) '()][else (choose-path-v2 (search-bt-path-v2 k (node-left tree))

(search-bt-path-v2 k (node-right tree)))]))

(define (choose-path-v2 left-path right-path)(cond [(list? left-path) (cons 'left left-path)]

[(list? right-path) (cons 'right right-path)][else false]))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

20/91 11: Trees CS 135

Page 23: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Binary search trees

We will now make one change that can make searching much more efficient. Thischange will create a tree structure known as a binary search tree (BST).

For any given collection of keys, there is more than one possible tree.

How the keys are placed in a tree can improve the running time of searching thetree when compared to searching the same items in a list.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

21/91 11: Trees CS 135

Page 24: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

;; A Binary Search Tree (BST) is one of:;; ? empty;; ? a Node

(define-struct node (key left right));; A Node is a (make-node Nat BST BST);; Requires: key > every key in left BST;; key < every key in right BST

The BST ordering property:

key is greater than every key in left.

key is less than every key in right.

Note: the ordering property holds in every subtree

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

22/91 11: Trees CS 135

Page 25: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> A BST example

(make-node 5(make-node 1 empty empty)(make-node 7

(make-node 6 empty empty)(make-node 14 empty empty)))

51 7

1465

71

146

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

23/91 11: Trees CS 135

Page 26: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

There can be several BSTs holding a particular set of keys.

5

1 14

6

51 7

146

775 14

61

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

24/91 11: Trees CS 135

Page 27: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Making use of the ordering property

Main advantage: for certain computations, one of the recursive functionapplications in the template can always be avoided.

This is more efficient (sometimes considerably so).

In the following slides, we will demonstrate this advantage for searching andadding.

We will write the code for searching, and briefly sketch adding, leaving you to writethe Racket code.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

25/91 11: Trees CS 135

Page 28: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Searching in a BST

How do we search for a key n in a BST? We reason using the data definition of BST.

If the BST is empty, then n is not in the BST.

If the BST is of the form (make-node k left right), and k equals n,then we have found it.Otherwise it might be in either the left or right subtree.

If n < k, then n must be in left if it is present at all,and we only need to recursively search in left.If n > k, then n must be in right if it is present at all,and we only need to recursively search in right.

Either way, we save one recursive function application.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

26/91 11: Trees CS 135

5

1 6

140 3

Page 29: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

search-bst

;; (search-bst n t) produces true if n is in t; false otherwise.;; search-bst: Nat BST → Bool(define (search-bst n t)(cond[(empty? t) false]

[(= n (node-key t)) true][(< n (node-key t)) (search-bst n (node-left t))][(> n (node-key t)) (search-bst n (node-right t))]))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

27/91 11: Trees CS 135

5

1 6

140 3

Page 30: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Exercise 3

Write a function (count-smaller n t) that consumes a Nat and a BST, and returnsthe number of keys in t that are less than n.

(define example(make-node 5

(make-node 1 empty empty)(make-node 7

(make-node 6 empty empty)(make-node 14 empty empty))))

(check-expect (count-smaller 8 example) 4)(check-expect (count-smaller 1 example) 0)(check-expect (count-smaller 100 example) 5)

For efficiency: don’t always search both children!

Page 31: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Adding to a BST

How do we add a new key, n, to a BST t?

Reasoning from the data definition for a BST:

If t is empty, then the result is a BST with only one node containing n.

If t is of the form (make-node k left right) and k = n, the key is already inthe tree and we can simply produce t.Otherwise, n must go in either the left or right subtree.

If n < k, then the new key must be added to left.If n > k, then the new key must be added to right.

Again, we need only make one recursive function application.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

28/91 11: Trees CS 135

Page 32: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Creating a BST from a list

How do we create a BST from a list of keys?

We reason using the data definition of a list.

If the list is empty, the BST is empty.

If the list is of the form (cons k lst), we add the key k to the BST created from thelist lst. The first key in the list is inserted last.

It is also possible to write a function that inserts keys in the opposite order.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

29/91 11: Trees CS 135

Page 33: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Binary search trees in practice

If the BST has all left subtrees empty, it looks and behaves like a sorted list, andthe advantage is lost.

In later courses, you will see ways to keep a BST “balanced” so that “most” nodeshave nonempty left and right children. We will also cover better ways to analyzethe efficiency of algorithms and operations on data structures.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

30/91 11: Trees CS 135

Page 34: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Exercise 4

Practise problems on binary search trees:

Write a function, bst-min, which consumes a non-empty BST and producesthe minimum value in the tree.

Write a function, bst-max, which consumes a non-empty BST and producesthe maximum value in the tree.

Write a function, bst-add, which consumes a BST, t, and a new key, n. Itproduces a BST with all of the keys found in t as well as n. If n happens toalready exist in t it produces a BST just like t.

Write a function, bst-from-list, which consumes a (listof Nat) andproduces a BST containing those same values. Use simple recursion.

Write a function, bst-from-list/acc, which consumes a (listof Nat) andproduces a BST containing those same values. Use accumulative recursion.

Rewrite search-bst without a cond (using a single Boolean expression).

Page 35: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Augmenting trees

So far nodes have been (define-struct node (key left right)).

We can augment the node with additional data:(define-struct node (key val left right)).

The name val is arbitrary – choose any name you like.

The type of val is also arbitrary: could be a number, string, structure, etc.

You could augment with multiple values.

The set of keys remains unique.

The tree could have duplicate values.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

31/91 11: Trees CS 135

Page 36: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

BST dictionaries

An augmented BST can serve as a dictionary that can perform significantly betterthan an association list.

Recall from Module 08 that a dictionary stores a set of (key, value) pairs, with atmost one occurrence of any key. A dictionary supports lookup, add, and remove

operations.

We implemented dictionaries using an association list, a list of two-element lists.Seach could be inefficient for large lists.

We need to modify node to include the value associated with the key. search needsto return the associated value, if found.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

32/91 11: Trees CS 135

Page 37: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> search-bst-dict

(define-struct node (key val left right));; A binary search tree dictionary (BSTD) is either:;; * empty;; * (make-node Nat Str BSTD BSTD)

;; (search-bst-dict k t) produces the value associated with k;; if k is in t; false otherwise.;; search-bst-dict: Nat BSTD → (anyof Str false)(define (search-bst-dict k t)(cond[(empty? t) false]

[(= k (node-key t)) (node-val t)][(< k (node-key t)) (search-bst-dict k (node-left t))][(> k (node-key t)) (search-bst-dict k (node-right t))]))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

33/91 11: Trees CS 135

Page 38: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> search-bst-dict tests

(define test-tree (make-node 5 "Susan"(make-node 1 "Juan" empty empty)(make-node 14 "David"

(make-node 6 "Lucy" empty empty)empty)))

(check-expect (search-bst-dict 5 empty) false)(check-expect (search-bst-dict 5 test-tree) "Susan")(check-expect (search-bst-dict 6 test-tree) "Lucy")(check-expect (search-bst-dict 2 test-tree) false)

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

34/91 11: Trees CS 135

Page 39: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Evolutionary trees

Evolutionary trees are augmented binary trees that show the evolutionaryrelationships between species. Biologists believe that all life on Earth is part of asingle evolutionary tree, indicating common ancestry.

Leaves represent a current species. They are augmented with a name andwhether the species is endangered.

Internal nodes represent a hypothesized common ancestor species that splitinto two new species. Internal nodes are augmented with a name and an estimateof how long ago the split took place (in millions of years).

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

35/91 11: Trees CS 135

Page 40: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Evolutionary trees

Evolutionary trees are constructed byevolutionary biologists.

Start with current species.

Based on common attributes(including DNA sequences),hypothesize common ancestorspecies.

Keep going with more and morecommon ancestor species,

back to a single common ancestor(the root).

Current Species

Hyp

othe

tical

Com

mon

Anc

esto

rs

humanfalse

chimptrue

ratfalse

fruitflyfalse

chickenfalse

wormfalse

cranetrue

Tim

e

early primates

5

early mammals

65

early vertebrates

320

multi-celled organisms

535 early invertebrates

530

early birds 100

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

36/91 11: Trees CS 135

Page 41: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> A very incomplete, sample evolutionary tree

Current Species

Hyp

othe

tical

Com

mon

Anc

esto

rs

humanfalse

chimptrue

ratfalse

fruitflyfalse

chickenfalse

wormfalse

cranetrue

Tim

e

early primates

5

early mammals

65

early vertebrates

320

multi-celled organisms

535 early invertebrates

530

early birds 100

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

37/91 11: Trees CS 135

Page 42: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> The fine print

We’ve simplified a lot...

The correct term is phylogenetic tree.

Evolutionary trees are built with incomplete data and theories, so biologistshave created many different trees.

Leaves could represent species that became extinct before splitting intocurrent species. We’re going to ignore that possibility.

This is an active area of research; see Wikipedia on “phylogenetic tree”.UWaterloo has a CS research group that works on these problems (including atool to build these trees). See https://uwaterloo.ca/bioinformatics-group/.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

38/91 11: Trees CS 135

Page 43: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

» Representing evolutionary trees

Internal nodes each have exactly two children. Each internal node has:

the name of the common ancestor species

how long ago the common ancestor split into two new species

the two species that resulted from the split

Leaves have:

the name of the current species

the endangerment status (true if endangered; false otherwise)

The order of children does not matter.

The structure of the tree is dictated by a hypothesis about evolution.Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

39/91 11: Trees CS 135

Page 44: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

» Data definitions for evolutionary trees

;; An EvoTree (Evolutionary Tree) is one of:;; * a Current (current species);; * an Ancestor (common ancestor species)

(define-struct current (name endangered));; A Current is a (make-current Str Bool)(define-struct ancestor (name age left right));; An Ancestor is a (make-ancestor Str Num EvoTree EvoTree)

Note that the Ancestor data definition uses a pair of EvoTrees.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

40/91 11: Trees CS 135

Page 45: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

» Constructing the example evolutionary tree (1/2)

(define-struct current (name endangered));; A Current is a (make-current Str Bool)(define-struct ancestor (name age left right));; An Ancestor is a (make-ancestor Str Num EvoTree EvoTree)

(define human (make-current "human" false))(define chimp (make-current "chimp" true))(define rat (make-current "rat" false))(define crane (make-current "crane" true))(define chicken (make-current "chicken" false))(define worm (make-current "worm" false))(define fruit-fly (make-current "fruit fly" false))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

41/91 11: Trees CS 135

Page 46: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

» Constructing the example evolutionary tree (2/2)

(define e-primates (make-ancestor "early primates" 5 human chimp))(define e-mammals (make-ancestor "early mammals" 65 e-primates rat))(define e-birds (make-ancestor "early birds" 100 crane chicken))(define e-vertebrates(make-ancestor "early vertibrates" 320 e-mammals e-birds))

(define e-invertebrates(make-ancestor "early invertibrates" 530 worm fruit-fly))

(define mco(make-ancestor "multi-celled organisms"

535 e-vertebrates e-invertebrates))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

42/91 11: Trees CS 135

Page 47: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> EvoTree Template (1/3)

;; An EvoTree (Evolutionary Tree) is one of:;; * a Current (current species);; * an Ancestor (common ancestor species)

(define-struct current (name endangered));; A Current is a (make-current Str Bool)(define-struct ancestor (name age left right));; An Ancestor is a (make-ancestor Str Num EvoTree EvoTree)

;; evotree-template: EvoTree → Any(define (evotree-template t)(cond [(current? t) (current-template t)]

[(ancestor? t) (ancestor-template t)]))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

43/91 11: Trees CS 135

Page 48: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

» EvoTree Template (2/3)

;; current-template: Current → Any(define (current-template cs)(... (current-name cs) ...

(current-endangered cs) ...))

;; ancestor-template: Ancestor → Any(define (ancestor-template as)(... (ancestor-name as) ...

(ancestor-age as) ...(ancestor-left as) ...(ancestor-right as) ...))

This is a straightforwardimplementation based on thedata definition.

It’s also a good strategy totake a complicated problem(dealing with an EvoTree) anddecompose it into simplerproblems (dealing with aCurrent or an Ancestor).

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

44/91 11: Trees CS 135

Page 49: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

» EvoTree Template (3/3)

We know that (ancestor-left as) and (ancestor-right as) are EvoTrees, soapply the EvoTree-processing function to them.

;; ancestor-template: Ancestor → Any(define (ancestor-template as)(... (ancestor-name as) ...

(ancestor-age as) ...(evotree-template (ancestor-left as)) ...(evotree-template (ancestor-right as)) ...))

ancestor-template uses evotree-template and evotree-template usesancestor-template. This is called mutual recursion.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

45/91 11: Trees CS 135

Page 50: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> A function on EvoTrees (1/2)

This function counts the number of current species within an evotree.

;; (count-current-species t): Counts the number of current species;; (leaves) in the EvoTree t.(check-expect (count-current-species mco) 7)(check-expect (count-current-species human) 1)

;; count-current-species: EvoTree → Nat(define (count-current-species t)(cond [(current? t) (count-current t)]

[(ancestor? t) (count-ancestor t)]))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

46/91 11: Trees CS 135

Current Species

Hyp

othe

tical

Com

mon

Anc

esto

rs

humanfalse

chimptrue

ratfalse

fruitflyfalse

chickenfalse

wormfalse

cranetrue

Tim

e

early primates

5

early mammals

65

early vertebrates

320

multi-celled organisms

535 early invertebrates

530

early birds 100

Page 51: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

» A function on EvoTrees (2/2)

;; count-current Current → Nat(define (count-current t)1)

;; count-ancestor Ancestor → Nat(define (count-ancestor t)(+ (count-current-species (ancestor-left t))

(count-current-species (ancestor-right t))))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

47/91 11: Trees CS 135

Page 52: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Traversing a tree

A tree traversal refers to the process of visiting each node in a tree exactly once.They are often classified by the order in which the nodes are visited:

pre-order: visit the root, then each subtree

in-order: visit one subtree, the root, and then the other subtree

post-order: visit both subtrees, then the root

The increment example from binary trees is one example of a pre-order traversal.

We’ll now traverse an EvoTree to produce a list of all the names it contains.

We’ll solve this problem two different ways: using append and using accumulativerecursion.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

48/91 11: Trees CS 135

Page 53: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

» list-names

;; list-names: EvoTree → (listof Str)(define (list-names t)(cond [(current? t) (list-cnames t)]

[(ancestor? t) (list-anames t)]))

;; list-cnames: Current →(define (list-cnames cs)(... (current-name cs) ...))

;; list-anames: Ancestor →(define (list-anames as)(... (ancestor-name as) ...

(list-names (ancestor-left as)) ...(list-names (ancestor-right as)) ...))

The contracts giveimportant informationthat can guide thedevelopment.

What are they?

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

49/91 11: Trees CS 135

Page 54: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

» list-names with an accumulator (1/2)

;; list-names: EvoTree → (listof Str)(define (list-names t)(list-names/acc t '()))

;; list-names/acc: EvoTree (listof Str) → (listof Str)(define (list-names/acc t names)(cond [(current? t) (list-cnames t names)]

[(ancestor? t) (list-anames t names)]))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

50/91 11: Trees CS 135

Page 55: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

» list-names with an accumulator (2/2)

;; list-cnames: Current (listof Str) → (listof Str)(define (list-cnames cs names)(cons (current-name cs) names))

;; list-anames: Ancestor (listof Str) → (listof Str)(define (list-anames as names)(cons (ancestor-name as)

(list-names/acc (ancestor-left as)(list-names/acc (ancestor-right as) names))))

;; Tests(check-expect (list-names human) '("human"))(check-expect (list-names e-mammals)

'("early mammals" "early primates" "human" "chimp" "rat"))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

51/91 11: Trees CS 135

Page 56: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Practice problems with EvoTrees

Count the number of ancestors (internal nodes) that split less than n (million)years ago. For example, the sample tree has 4 ancestor species that split lessthan 400 million years ago.

Count the number of common ancestors for a given recent species.

Find the evolutionary path between the root of a (sub)tree and a currentspecies. For example, the path from mco to rat is'("multi-celled organism" "early vertebrates" "early mammals" "rat").

Modify list-names to produce the names of only endangered species.

Modify list-names/acc to produces the other two traversals. (Hint: how elsecan you join (ancestor-name as) to the list of names seen so far?)

Page 57: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Binary expression trees

The expression ((2 ∗ 6) + (5 ∗ 2))/(5− 3) can be represented as abinary expression tree:

/+ -

35* *

2562

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

52/91 11: Trees CS 135

Page 58: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Representing binary arithmetic expressions

Internal nodes each have exactly two children.

Leaves have number labels.

Internal nodes have symbol labels.

We care about the order of children.

The structure of the tree is dictated by the expression.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

53/91 11: Trees CS 135

Page 59: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Representing binary arithmetic expressions

;; A binary arithmetic expression (BinExp) is one of:;; * a Num;; * a BINode

(define-struct binode (op left right));; A Binary arithmetic expression Internal Node (BINode);; is a (make-binode (anyof '* '+ '/ '-) BinExp BinExp)

Some examples of binary arithmetic expressions:

5(make-binode '* 2 6)(make-binode '+ 2 (make-binode '- 5 3))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

54/91 11: Trees CS 135

Page 60: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

» A more complex example

(make-binode '/(make-binode '+ (make-binode '* 2 6)

(make-binode '* 5 2))(make-binode '- 5 3))

/+ -

35* *

2562Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

55/91 11: Trees CS 135

Page 61: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Templates for binary arithmetic expressions

;; binexp-template: BinExp → Any(define (binexp-template ex)(cond [(number? ex) (... ex ...)]

[(binode? ex) (binode-template ex)]))

;; binode-template: BINode → Any(define (binode-template node)(... (binode-op node) ...

(binexp-template (binode-left node)) ...(binexp-template (binode-right node)) ...))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

56/91 11: Trees CS 135

Page 62: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Evaluating expressions (1/2)

;; (eval ex) evaluates the expression ex and produces its value.(check-expect (eval 5) 5)(check-expect (eval (make-binode '+ 2 5)) 7)(check-expect (eval (make-binode '/ (make-binode '- 10 2)

(make-binode '+ 2 2))) 2)

;; eval: BinExp → Num(define (eval ex)(cond [(number? ex) ex]

[(binode? ex) (eval-binode ex)]))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

57/91 11: Trees CS 135

Page 63: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Evaluating expressions (2/2)

;; (eval-binode node) evaluates the expression represented by node.;; eval-binode BINode → Num(define (eval-binode node)(cond [(symbol=? '* (binode-op node))

(* (eval (binode-left node)) (eval (binode-right node)))][(symbol=? '/ (binode-op node))(/ (eval (binode-left node)) (eval (binode-right node)))][(symbol=? '+ (binode-op node))(+ (eval (binode-left node)) (eval (binode-right node)))][(symbol=? '- (binode-op node))(- (eval (binode-left node)) (eval (binode-right node)))]))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

58/91 11: Trees CS 135

Page 64: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

» Eval, refactored

(define (eval ex)(cond [(number? ex) ex]

[(binode? ex) (eval-binode (binode-op ex)(eval (binode-left ex))(eval (binode-right ex)))]))

(define (eval-binode op left-val right-val)(cond [(symbol=? op '*) (* left-val right-val)]

[(symbol=? op '/) (/ left-val right-val)][(symbol=? op '+) (+ left-val right-val)][(symbol=? op '-) (- left-val right-val)]))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

59/91 11: Trees CS 135

Page 65: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

General trees

Binary trees can be used for a large variety of application areas.

One limitation is the restriction on the number of children.

How might we represent a node that can have up to three children?

What if there can be any number of children?

Trees with an arbitrary number of children (subtrees) in each node are calledgeneral trees.

Our example of a general tree will be arithmetic expressions.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

60/91 11: Trees CS 135

Page 66: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

General arithmetic expressions

For binary arithmetic expressions, we formed binary trees.

Racket expressions using the functions + and ∗ can have an unbounded numberof arguments. For example,

(+ (* 4 2)3(+ 5 1 2)2)

For simplicity, we will restrict the operations to + and ∗.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

61/91 11: Trees CS 135

Page 67: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Example tree

(+ (* 4 2)3(+ 5 1 2)2)

+

*

21524

23+

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

62/91 11: Trees CS 135

Page 68: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Representing general arithmetic expression trees

For a binary arithmetic expression, we defined a structure with three fields: theoperation, the first argument, and the second argument.

For a general arithmetic expression, we define a structure with two fields: theoperation and a list of arguments (which is a list of arithmetic expressions).

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

63/91 11: Trees CS 135

Page 69: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Representing general trees

;; An Arithmetic Expression (AExp) is one of:;; * Num;; * OpNode

(define-struct opnode (op args));; An OpNode (operator node) is a;; (make-opnode (anyof '* '+) (listof AExp)).

AExp is defined using OpNode and OpNode is defined using AExp. This will lead tomutual recursion.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

64/91 11: Trees CS 135

+

*

21524

23+

Page 70: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Examples of arithmetic expressions

3

(make-opnode '* (list 3 4 5))

(make-opnode'+ (list (make-opnode '* '(4 2))

3(make-opnode '+ '(5 1 2))2))

543

*

+

*

21524

23+

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

65/91 11: Trees CS 135

Page 71: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Developing eval

;; (eval exp) evaluates the arithmetic expression exp.;; Examples:(check-expect (eval 5) 5)(check-expect (eval (make-opnode '+ (list 1 2 3 4))) 10)(check-expect (eval (make-opnode '* (list 2 3 4))) 24)(check-expect (eval (make-opnode '+ (list 1

(make-opnode '* (list 2 3))3))) 10)

;; eval: AExp → Num(define (eval exp)

...)

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

66/91 11: Trees CS 135

Page 72: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Completed eval and apply (1/3)

;; (eval exp) evaluates the arithmetic expression exp.;; Examples:(check-expect (eval 5) 5)(check-expect (eval (make-opnode '+ (list 1 2 3 4))) 10)(check-expect (eval (make-opnode '* (list 2 3 4))) 24)(check-expect (eval (make-opnode '+ (list 1

(make-opnode '* (list 2 3))3))) 10)

;; eval: AExp → Num(define (eval exp)(cond [(number? exp) exp]

[(opnode? exp) (apply (opnode-op exp)(opnode-args exp))]))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

67/91 11: Trees CS 135

Page 73: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Completed eval and apply (2/3)

;; (apply op args) applies the arithmetic operator op to args.;; Examples:(check-expect (apply '+ (list 1 2 3 4)) 10)(check-expect (apply '* (list 2 3 4)) 24)(check-expect (apply '+ (list 1 (make-opnode '* (list 2 3)))) 7)(check-expect (apply '+ (list )) 0)(check-expect (apply '* (list )) 1)

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

68/91 11: Trees CS 135

Page 74: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Completed eval and apply (3/3)

1 ;; apply: (anyof '+ '*) (listof AExp) → Num2 (define (apply op args)3 (cond [(empty? args) (cond [(symbol=? op '+) 0]4 [(symbol=? op '*) 1])]5 [(symbol=? op '+) (+ (eval (first args))6 (apply op (rest args)))]7 [(symbol=? op '*) (* (eval (first args))8 (apply op (rest args)))]))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

69/91 11: Trees CS 135

Page 75: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Condensed trace of aexp evaluation (1/4)

(eval (make-opnode '+ (list (make-opnode '* '(3 4))(make-opnode '* '(2 5)))))

⇒ (apply '+ (list (make-opnode '* '(3 4))(make-opnode '* '(2 5))))

⇒ (+ (eval (make-opnode '* '(3 4)))(apply '+ (list (make-opnode '* '(2 5)))))

⇒ (+ (apply '* '(3 4))(apply '+ (list (make-opnode '* '(2 5)))))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

70/91 11: Trees CS 135

Page 76: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Condensed trace of aexp evaluation (2/4)

⇒ (+ (* (eval 3) (apply '* '(4)))(apply '+ (list (make-opnode '* '(2 5)))))

⇒ (+ (* 3 (apply '* '(4)))(apply '+ (list (make-opnode '* '(2 5)))))

⇒ (+ (* 3 (* (eval 4) (apply '* empty)))(apply '+ (list (make-opnode '* '(2 5)))))

⇒ (+ (* 3 (* 4 (apply '* empty)))(apply '+ (list (make-opnode '* '(2 5)))))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

71/91 11: Trees CS 135

Page 77: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Condensed trace of aexp evaluation (3/4)

⇒ (+ (* 3 (* 4 1))(apply '+ (list (make-opnode '* '(2 5)))))

⇒ (+ 12(apply '+ (list (make-opnode '* '(2 5)))))

⇒ (+ 12 (+ (eval (make-opnode '* '(2 5)))(apply '+ empty)))

⇒ (+ 12 (+ (apply '* '(2 5))(apply '+ empty)))

⇒ (+ 12 (+ (* (eval 2) (apply '* '(5)))(apply '+ empty)))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

72/91 11: Trees CS 135

Page 78: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Condensed trace of aexp evaluation (4/4)

⇒ (+ 12 (+ (* 2 (apply '* '(5)))(apply '+ empty)))

⇒ (+ 12 (+ (* 2 (* (eval 5) (apply '* empty)))(apply '+ empty)))

⇒ (+ 12 (+ (* 2 (* 5 (apply '* empty)))(apply '+ empty)))

⇒ (+ 12 (+ (* 2 (* 5 1))(apply '+ empty)))

⇒ (+ 12 (+ 10 (apply '+ empty)))⇒ (+ 12 (+ 10 0)) ⇒ 22

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

73/91 11: Trees CS 135

Page 79: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Alternate data definition

In Module 10, we saw how a list could be used instead of a student structure.

Here we could use a similar idea to replace the structure opnode and the datadefinitions for AExp.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

74/91 11: Trees CS 135

Page 80: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

» Alternate data definition

;; An alternate arithmetic expression (AltAExp) is one of:;; * a Num;; * (cons (anyof '* '+) (listof AltAExp))

Each expression is a list consisting of a symbol (the operation) and a list ofexpressions.

3'(+ 3 4)'(+ (* 4 2) 3 (+ 5 1 2) 2)

Developing the alternative versions of eval and apply is left as an exercise.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

75/91 11: Trees CS 135

Page 81: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Structuring data using mutual recursion

Mutual recursion arises when complex relationships among data result in crossreferences between data definitions.

The number of data definitions can be greater than two.

Structures and lists may also be used.

In each case:

create templates from the data definitions and

create one function for each template.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

76/91 11: Trees CS 135

Page 82: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Other uses of general trees

We can generalize from allowing only two arithmetic operations and numbers toallowing arbitrary functions and variables.

In effect, we have the beginnings of a Racket interpreter.

But beyond this, the type of processing we have done on arithmetic expressionscan be applied to tagged hierarchical data, of which a Racket expression is justone example.

Organized text and Web pages provide other examples.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

77/91 11: Trees CS 135

Page 83: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

» Representing organized text

'(chapter(section(paragraph "This is the first sentence."

"This is the second sentence.")(paragraph "We can continue in this manner."))

(section ...)...

)

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

78/91 11: Trees CS 135

Page 84: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

» Representing a web page

'(webpage(title "CS 135: Designing Functional Programs")(paragraph "For a course description,"

(link "click here." "desc.html")"Enjoy the course!")

(horizontal-line)(paragraph "(Last modified yesterday.)"))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

79/91 11: Trees CS 135

Page 85: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Nested lists

We have discussed flat lists (no nesting):

'(a 1 "hello" x)

and lists of lists (one level of nesting):

'((1 "a") (2 "b") (3 "c"))

We now consider nested lists (arbitrary nesting):

'((1 (2 3))4(5 (6 7 8) 9 ()))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

80/91 11: Trees CS 135

Page 86: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Visualizing nested lists

It is often useful to visualize a nested list as a tree, in which the leaves correspondto the elements of the list, and the internal nodes indicate the nesting:

'()

'(1) 1

'(1 2 3) 1 2 3

'((1 2) 3 (4 ()))

3

21 4

951

4

86 732'((1 (2 3)) 4 (5 (6 7 8) 9 ()))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

81/91 11: Trees CS 135

Page 87: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Data definition for nested lists

Sample nested lists:

'()'((1 2) 3 (4 ()))'(1 2 3)'(1 (2 3) 4)

Observations:

A nested list might be emptyThe first item of a non-empty nested list is either:

a nested lista single item (a number, not a list)

The rest of a non-empty nested list is a nested list

;; A nested list of numbers (Nest-List-Num) is one of:;; * empty;; * (cons Nest-List-Num Nest-List-Num);; * (cons Num Nest-List-Num)

This can be generalized to generic types: (nested-listof X).

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

82/91 11: Trees CS 135

Page 88: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Template for nested lists

The template follows from the data definition.

;; nest-lst-template: (nested-listof X) → Any(define (nest-lst-template lst)(cond [(empty? lst) ...]

[(list? (first lst)) (... (nest-lst-template (first lst)) ...(nest-lst-template (rest lst)) ...)]

[else (... (first lst) ...(nest-lst-template (rest lst)) ...)]))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

83/91 11: Trees CS 135

Page 89: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> The function count-items

;; (count-items nl) counts the number of items in nl.;; Examples:(check-expect (count-items '()) 0)(check-expect (count-items '((10 20) 30)) 3)(check-expect (count-items '((10 20) () "thirty")) 3)

;; count-items: (nested-listof X) → Nat(define (count-items lst)(cond [(empty? lst) 0]

[(list? (first lst)) (+ (count-items (first lst))(count-items (rest lst)))]

[else (+ 1(count-items (rest lst)))]))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

84/91 11: Trees CS 135

Page 90: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

» Condensed trace of count-items

(count-items '((10 20) 30))⇒ (+ (count-items '(10 20)) (count-items '(30)))⇒ (+ (+ 1 (count-items '(20))) (count-items '(30)))⇒ (+ (+ 1 (+ 1 (count-items '()))) (count-items '(30)))⇒ (+ (+ 1 (+ 1 0)) (count-items '(30)))⇒ (+ (+ 1 1) (count-items '(30)))⇒ (+ 2 (count-items '(30)))⇒ (+ 2 (+ 1 (count-items '())))⇒ (+ 2 (+ 1 0)) ⇒ (+ 2 1) ⇒ 3

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

85/91 11: Trees CS 135

Page 91: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Flattening a nested list

flatten produces a flat list from a nested list.

;; (flatten lst) produces a flat list with all the elements of lst.;; Examples:(check-expect (flatten '(1 2 3)) '(1 2 3))(check-expect (flatten '((1 2 3) (a b c))) '(1 2 3 a b c))(check-expect (flatten '((1 2 3) () (a (b c)))) '(1 2 3 a b c))

;; flatten: (nested-listof X) → (listof X)(define (flatten lst)

We make use of the built-in Racket function append.

(append '(1 2) '(3 4)) ⇒ '(1 2 3 4)

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

86/91 11: Trees CS 135

Page 92: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

> Flattening a nested list

;; (flatten lst) produces a flat list with all the elements of lst.;; Examples:(check-expect (flatten '(1 2 3)) '(1 2 3))(check-expect (flatten '((1 2 3) (a b c))) '(1 2 3 a b c))(check-expect (flatten '((1 2 3) () (a (b c)))) '(1 2 3 a b c))

;; flatten: (nested-listof X) → (listof X)(define (flatten lst)(cond [(empty? lst) empty]

[(list? (first lst)) (append (flatten (first lst))(flatten (rest lst)))]

[else (cons (first lst)(flatten (rest lst)))]))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

87/91 11: Trees CS 135

Page 93: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

» Condensed trace of flatten

(flatten '((10 20) 30))⇒ (append (flatten '(10 20)) (flatten '(30)))⇒ (append (cons 10 (flatten '(20))) (flatten '(30)))⇒ (append (cons 10 (cons 20 (flatten '()))) (flatten '(30)))⇒ (append (cons 10 (cons 20 empty)) (flatten '(30)))⇒ (append (cons 10 (cons 20 empty)) (cons 30 (flatten '())))⇒ (append (cons 10 (cons 20 empty)) (cons 30 empty))⇒ (cons 10 (cons 20 (cons 30 empty)))

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

88/91 11: Trees CS 135

Page 94: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Exercise 6

Following the template, write a function that adds up all the values in a(nested-listof Num).

(check-expect (nest-lst-sum '(1 1)) 2)(check-expect (nest-lst-sum '(1 2 (3 4) () 7 ((1 4) 1))) 23)

Following the template, write a function that calculates the maximum depth ofa (nested-listof X).

(check-expect (nl-max-depth '()) 0)(check-expect (nl-max-depth '(())) 1)(check-expect (nl-max-depth '(1)) 1)(check-expect (nl-max-depth '(1 (1 2))) 2)

Page 95: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Exercise 7

Here is a definition of a generalized tree where any node can have many children:

(define-struct gnode (key children));; A GT (Generalized Tree) is a (make-gnode Nat (listof GT))

Write a function reverse-gt which consumes a GT and produces its reverse.Consider a GT node with k children at positions 0 to (k − 1). The reverse of thisnode is the same node except that each child that was at position i is now atposition (k − i), for 0 ≤ i < k . The reverse of a GT is the result of each node beingreversed.

81 66 48 11

37 12

78

81664811

3712

78

Page 96: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Exercise 8

Here is a definition of a generalized tree where any node can have many children:

(define-struct gnode (key children));; A GT (Generalized Tree) is a (make-gnode Nat (listof GT))

A node’s level is the number of edges from the root to the node. Ln is the set of allnodes at level n. Write a function most-populated-level that consumes a GT andproduces a pair based on the set of nodes, Ln, that contains the most nodes. Thefirst member of the pair is n and the second member is the size of Ln.

For example, when called on the treebelow, most-populated-levelproduces '(2 6) .

55

47

25

10 13

14

31 84

82

78

39 33

38

32 34 36

15

Page 97: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Goals of this module (1/2)

You should be familiar with tree terminology.

You should understand the data definitions for binary trees, binary searchtrees, evolutionary trees, binary arithmetic expressions, general arithmeticexpressions, and nested lists.

You should understand how the templates are derived from those definitions,and how to use the templates to write functions that consume those types ofdata.

You should understand the definition of a binary search tree and its orderingproperty.

You should be able to write functions which consume binary search trees,including those sketched (but not developed fully) in lecture.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

89/91 11: Trees CS 135

Page 98: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Goals of this module (2/2)

You should be able to develop and use templates for other binary trees, notnecessarily presented in lecture.

You should understand the idea of mutual recursion for both examples given inlecture and new ones that might be introduced in lab, assignments, or exams.

You should be able to develop templates from mutually recursive datadefinitions, and to write functions using the templates.

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

90/91 11: Trees CS 135

Page 99: Readings: Topics - University of Waterloocs135/cc/lectures/post1... · 2020. 12. 18. · > Tree terminology (1/2) nodes root edges A tree is a set of nodes and edges where an edge

Summary: built-in functions

The following functions and special forms have been introduced in this module:

You should complete all exercises and assignments using only these and thefunctions and special forms introduced in earlier modules, which are:* + - ... / < <= = > >= abs add1 and append boolean? ceiling char=? char?

check-error check-expect check-within cond cons cons? define define-structeighth else empty? equal? error even? exp expt fifth first floor fourthinteger? length list list->string list? max member? min negative? notnumber->string number? odd? or positive? quotient remainder rest secondseventh sixth sqr sqrt string->list string-append string-downcasestring-length string-upcase string<=? string<? string=? string>=? string>?string? sub1 substring symbol=? symbol? third zero?

Examples Binary Trees BSTs Augmenting BinExpr General Trees Nested lists

91/91 11: Trees CS 135