Trees. Example: Binary expression trees. Example: Evolution trees. Readings: HtDP, sections 14, 15, 16.

Similar documents
Trees. Readings: HtDP, sections 14, 15, 16.

Trees. Binary arithmetic expressions. Visualizing binary arithmetic expressions. ((2 6) + (5 2))/(5 3) can be defined in terms of two smaller

Module 9: Binary trees

Module 8: Binary trees

Module 10: General trees

CS115 - Module 10 - General Trees

Module 9: Trees. If you have not already, make sure you. Read How to Design Programs Sections 14, 15, CS 115 Module 9: Trees

CS115 - Module 8 - Binary trees

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

Working with recursion. From definition to template. Readings: HtDP, sections 11, 12, 13 (Intermezzo 2).

Working with recursion

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction

Types of recursion. Structural vs. general recursion. Pure structural recursion. Readings: none. In this module: learn to use accumulative recursion

Graphs. Readings: Section 28. CS 135 Fall : Graphs 1

Graphs. Directed graphs. Readings: Section 28

Lists. Readings: HtDP, sections 9 and 10. Avoid 10.3 (uses draw.ss). CS 135 Winter : Lists 1

Types of recursion. Readings: none. In this module: a glimpse of non-structural recursion. CS 135 Winter : Types of recursion 1

Local definitions and lexical scope

Local definitions and lexical scope. Local definitions. Motivating local definitions. s(s a)(s b)(s c), where s = (a + b + c)/2.

Use recursion to write a function that duplicates the following function: (def (f L) (map (lambda (x) (+ (sqr x) x)) L))

Assignment: 7. Due: Language level: Allowed recursion:

Module 5: Lists. Readings: HtDP, Sections 9, 10.

CS 135 Fall 2018 Final Exam Review. CS 135 Fall 2018 Final Exam Review 1

Generative and accumulative recursion. What is generative recursion? Example revisited: GCD. Readings: Sections 25, 26, 27, 30, 31

How to Design Programs

Chapter 20: Binary Trees

Programming II (CS300)

Data Structures and Algorithms

CS61A Notes 02b Fake Plastic Trees. 2. (cons ((1 a) (2 o)) (3 g)) 3. (list ((1 a) (2 o)) (3 g)) 4. (append ((1 a) (2 o)) (3 g))

Module 8: Local and functional abstraction

Binary Trees

CS 115 Lecture Notes Winter 2019

BST Implementation. Data Structures. Lecture 4 Binary search trees (BST) Dr. Mahmoud Attia Sakr University of Ain Shams

CS 135 Winter 2018 Tutorial 8: Mutual recursion, nested lists, and local. CS 135 Winter 2018 Tutorial 8: Mutual recursion, nested lists, and local 1

Problem 1: Binary Trees: Flatten

CSE 214 Computer Science II Introduction to Tree

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

(Provisional) Lecture 08: List recursion and recursive diagrams 10:00 AM, Sep 22, 2017

Discussion 2C Notes (Week 8, February 25) TA: Brian Choi Section Webpage:

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example.

Linked Data Structures. Linked lists. Readings: CP:AMA The primary goal of this section is to be able to use linked lists and trees.

Intro. Scheme Basics. scm> 5 5. scm>

CS115 - Module 9 - filter, map, and friends


V Advanced Data Structures

Trees. Chapter 6. strings. 3 Both position and Enumerator are similar in concept to C++ iterators, although the details are quite different.

CS115 - Module 3 - Booleans, Conditionals, and Symbols

Friday Four Square! 4:15PM, Outside Gates

CSCI Trees. Mark Redekopp David Kempe

CS 171: Introduction to Computer Science II. Binary Search Trees

Linked Data Structures. Linked lists. Readings: CP:AMA The primary goal of this section is to be able to use linked lists and trees.

Uses for Trees About Trees Binary Trees. Trees. Seth Long. January 31, 2010

CS115 - Module 4 - Compound data: structures

Binary Search Trees. Analysis of Algorithms

V Advanced Data Structures

11 TREES DATA STRUCTURES AND ALGORITHMS IMPLEMENTATION & APPLICATIONS IMRAN IHSAN ASSISTANT PROFESSOR, AIR UNIVERSITY, ISLAMABAD

ITI Introduction to Computing II

Lecture 15 Binary Search Trees

Extra: B+ Trees. Motivations. Differences between BST and B+ 10/27/2017. CS1: Java Programming Colorado State University

A set of nodes (or vertices) with a single starting point

CS F-11 B-Trees 1

6.001 Notes: Section 31.1

Binary Trees, Binary Search Trees

CS 231 Data Structures and Algorithms Fall Binary Search Trees Lecture 23 October 29, Prof. Zadia Codabux

INF2220: algorithms and data structures Series 1

ITI Introduction to Computing II

2-3 and Trees. COL 106 Shweta Agrawal, Amit Kumar, Dr. Ilyas Cicekli

TREES. Trees - Introduction

User-defined Functions. Conditional Expressions in Scheme

6.001 Notes: Section 15.1

Algorithms. Deleting from Red-Black Trees B-Trees

UNIVERSITY OF TORONTO Faculty of Arts and Science. Midterm Sample Solutions CSC324H1 Duration: 50 minutes Instructor(s): David Liu.

Trees, Part 1: Unbalanced Trees

Binary Trees. Height 1

CSE341 Autumn 2017, Final Examination December 12, 2017

Algorithms in Systems Engineering ISE 172. Lecture 16. Dr. Ted Ralphs

HIERARCHICAL DATA What is a Tree? How is it different from a Deep List? When would you use one over the other?

CSI33 Data Structures

Lists. CS 5010 Program Design Paradigms Bootcamp Lesson 4.1

If you took your exam home last time, I will still regrade it if you want.

Environments

Trees. A tree is a directed graph with the property

Inductive Data Types

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

CS301 - Data Structures Glossary By

CSE341 Spring 2017, Final Examination June 8, 2017

CS1102: Macros and Recursion

Lecture 16: Binary Search Trees

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

Lecture 32. No computer use today. Reminders: Homework 11 is due today. Project 6 is due next Friday. Questions?

CSC/MAT-220: Lab 6. Due: 11/26/2018

Typed Racket: Racket with Static Types

Trees. Q: Why study trees? A: Many advance ADTs are implemented using tree-based data structures.

Trees. Eric McCreath

Algorithms and Data Structures (INF1) Lecture 8/15 Hua Lu

Maps; Binary Search Trees

2-3 Tree. Outline B-TREE. catch(...){ printf( "Assignment::SolveProblem() AAAA!"); } ADD SLIDES ON DISJOINT SETS

CSE 100 Advanced Data Structures

Richard Feynman, Lectures on Computation

Transcription:

Trees Readings: HtDP, sections 14, 15, 16. We will cover the ideas in the text using different examples and different terminology. The readings are still important as an additional source of examples. CS 135 Fall 2018 08: Trees 1 Example: Binary expression trees The expression ((2 6) + (5 2))/(5 3) can be represented as a tree: / + - * * 5 3 2 6 5 2 CS 135 Fall 2018 08: Trees 2 Example: Evolution trees Information related to the evolution of species can also be represented as a tree. This tree shows how species evolved to become new species. Animal 535 Primate 5 Mammal 65 Vertebrate 320 Bird 100 Invertebrate 530 Evolutionary Events human false chimp true rat false crane true chicken false worm false fruitfly false Most Recent Species CS 135 Fall 2018 08: Trees 3

Tree terminology label 5 root internal nodes siblings 1 8 parent leaves 6 subtree 14 child CS 135 Fall 2018 08: Trees 4 Characteristics of trees Number of children of internal nodes: exactly two at most two any number Labels: on all nodes just on leaves Order of children (matters or not) Tree structure (from data or for convenience) CS 135 Fall 2018 08: Trees 5 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 what language you use. Binary arithmetic expression trees and evolution trees are both examples of binary trees. We ll start with the simplest possible binary tree. It could be used to store a set of natural numbers. CS 135 Fall 2018 08: Trees 6

Drawing binary trees 5 1 6 5 1 6 14 Note: We will consistently use Nats in our binary trees, but it could be a symbol, string, struct,... 14 CS 135 Fall 2018 08: Trees 7 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 implement dictionaries. What is the template? CS 135 Fall 2018 08: Trees 8 Example functions on a binary tree Let us fill in the template to make a simple function: count how many nodes in the BT have a key equal to k : ;; count-nodes: BT Nat Nat (define (count-nodes tree k) (cond [(empty? tree) 0] [else (+ (cond [(equal? k (node-key tree)) 1] [else 0]) (count-nodes (node-left tree) k) (count-nodes (node-right tree) k))])) CS 135 Fall 2018 08: Trees 9

Add 1 to every key in a given 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)))])) CS 135 Fall 2018 08: Trees 10 Searching binary trees We are now ready to try to search our binary tree for a given key. It will produce true if it s 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. If either recursive search finds the key, produce true. Otherwise, produce false. CS 135 Fall 2018 08: Trees 11 Now we can fill in our BT template to write our search function: ;; search-bt: 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? CS 135 Fall 2018 08: Trees 12

Find the path to a key Write a function, search-bt-path, that searches for an item in the tree. As before, it will return false if the item is not found. However, if it is found search-bt-path will return a list of the symbols left and right indicating the path from the root to the item. CS 135 Fall 2018 08: Trees 13 6 3 10 2 45 3 9 5 (check-expect (search-bt-path 0 empty) false) (check-expect (search-bt-path 0 test-tree) false) (check-expect (search-bt-path 6 test-tree) ()) (check-expect (search-bt-path 9 test-tree) (right right left)) (check-expect (search-bt-path 3 test-tree) (left)) CS 135 Fall 2018 08: Trees 14 ;; search-bt-path: Nat BT (anyof false (listof Sym)) (define (search-bt-path k tree) (cond [(empty? tree) false] [(= k (node-key tree)) ()] [(list? (search-bt-path k (node-left tree))) (cons left (search-bt-path k (node-left tree)))] [(list? (search-bt-path k (node-right tree))) (cons right (search-bt-path k (node-right tree)))] [else false])) Double calls to search-bt-path. Uggh! CS 135 Fall 2018 08: Trees 15

;; search-bt-path: Nat BT (anyof false (listof Sym)) (define (search-bt-path k tree) (cond [(empty? tree) false] [(= k (node-key tree)) ()] [else (choose-path (search-bt-path k (node-left tree)) (search-bt-path k (node-right tree)))])) (define (choose-path path1 path2) (cond [(list? path1) (cons left path1)] [(list? path2) (cons right path2)] [else false])) CS 135 Fall 2018 08: Trees 16 Binary search trees We will now make one change that can make searching much more efficient. This change will create a 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 the tree when compared to searching the same items in a list. CS 135 Fall 2018 08: Trees 17 ;; 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. CS 135 Fall 2018 08: Trees 18

A BST example (make-node 5 (make-node 1 empty empty) (make-node 6 empty (make-node 14 empty empty))) 5 1 6 5 1 6 14 14 CS 135 Fall 2018 08: Trees 19 There can be several BSTs holding a particular set of keys. 5 5 1 6 1 14 14 6 CS 135 Fall 2018 08: Trees 20 Making use of the ordering property Main advantage: for certain computations, one of the recursive function applications 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 and adding. We will write the code for searching, and briefly sketch adding, leaving you to write the Racket code. CS 135 Fall 2018 08: Trees 21

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 l r), and k equals n, then we have found it. Otherwise it might be in either of the trees l, r. CS 135 Fall 2018 08: Trees 22 If n < k, then n must be in l if it is present at all, and we only need to recursively search in l. If n > k, then n must be in r if it is present at all, and we only need to recursively search in r. Either way, we save one recursive function application. CS 135 Fall 2018 08: Trees 23 ;; (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))])) CS 135 Fall 2018 08: Trees 24

Adding to a BST How do we add a new key, k, to a BST t? If t is empty, then the result is a BST with only one node. Otherwise t is of the form (make-node n l r). If k = n, the key is already in the tree and we can simply return t. If k < n, then the new key must be added to l, and if k > n, then the pair must be added to r. Again, we need only make one recursive function application. CS 135 Fall 2018 08: Trees 25 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 the list lst. The first key is inserted last. It is also possible to write a function that inserts keys in the opposite order. CS 135 Fall 2018 08: Trees 26 Binary search trees in practice If the BST has all left subtrees empty, it looks and behaves like a sorted list, and the advantage is lost. In later courses, you will see ways to keep a BST balanced so that most nodes have nonempty left and right children. We will also cover better ways to analyze the efficiency of algorithms and operations on data structures. CS 135 Fall 2018 08: Trees 27

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; could have duplicate values. CS 135 Fall 2018 08: Trees 28 BST dictionaries An augmented BST can serve as a dictionary that can perform significantly better than an association list. Recall from module 06 that a dictionary stores a set of (key, value) pairs, with at most 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 needs to return the associated value, if found. CS 135 Fall 2018 08: Trees 29 (define-struct node (key val left right)) ;; A binary search tree dictionary (BSTD) is either ;; empty or (make-node Nat String BSTD BSTD) ;; (search-bst-dict k t) produces the value associated with k ;; if k is in t; false otherwise. ;; search-bst: Nat BSTD anyof(string 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))])) CS 135 Fall 2018 08: Trees 30

(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) CS 135 Fall 2018 08: Trees 31 Evolutionary trees Evolutionary trees are another kind of augmented tree. Animal 535 Primate 5 Mammal 65 Vertebrate 320 Bird 100 Invertebrate 530 Evolutionary Events human false chimp true rat false crane true chicken false worm false fruitfly false Most Recent Species CS 135 Fall 2018 08: Trees 32 Evolutionary trees are binary trees that show the evolutionary relationships between species. Biologists believe that all life on Earth is part of a single evolutionary tree, indicating common ancestry. Internal nodes represent an evolutionary event when a common ancestor species split into two new species. Internal nodes are augmented with the common ancestor species name and an estimate of how long ago the evolutionary event took place (in millions of years). Leaves represent a most recent species. They are augmented with a name and whether the species is endangered. CS 135 Fall 2018 08: Trees 33

The fine print We ve simplified a lot... The correct terms are phylogenetic tree and speciation event. Nodes are often called taxonomic units. This is an active area of research; seek Wikipedia on phylogenetic tree. Evolutionary trees are built with incomplete data and theories, so there could be many different evolution trees. Leaves could represent extinct species that died off before splitting. Hence the term most recent species. CS 135 Fall 2018 08: Trees 34 Representing evolutionary trees Internal nodes each have exactly two children. Each internal node has the name of the common ancestor species and the estimated date of the evolutionary event. Leaves have names and endangerment status of the most recent species. The order of children does not matter. The structure of the tree is dictated by a hypothesis about evolution. CS 135 Fall 2018 08: Trees 35 Data definitions for evolutionary trees ;; A EvoTree (Evolution Tree) is one of: ;; a RSpecies (recent species) ;; a EvoEvent (evolutionary event) (define-struct rspecies (name endangered)) ;; A RSpecies is a (make-rspecies Str Bool) (define-struct evoevent (name age left right)) ;; A EvoEvent is a (make-evoevent Str Num EvoTree EvoTree) Note that the EvoEvent data definition uses a pair of EvoTrees. CS 135 Fall 2018 08: Trees 36

Constructing the example evolutionary tree (define-struct rspecies (name endangered)) (define-struct evoevent (name age left right)) (define human (make-rspecies "human" false)) (define chimp (make-rspecies "chimp" true)) (define rat (make-rspecies "rat" false)) (define crane (make-rspecies "crane" true)) (define chicken (make-rspecies "chicken" false)) (define worm (make-rspecies "worm" false)) (define fruit-fly (make-rspecies "fruit fly" false)) CS 135 Fall 2018 08: Trees 37 (define primate (make-evoevent "Primate" 5 human chimp)) (define mammal (make-evoevent "Mammal" 65 primate rat)) (define bird (make-evoevent "Bird" 100 crane chicken)) (define vertebrate (make-evoevent "Vertebrate" 320 mammal bird)) (define invertebrate (make-evoevent "Invertebrate" 530 worm fruit-fly)) (define animal (make-evoevent "Animal" 535 vertebrate invertebrate)) CS 135 Fall 2018 08: Trees 38 Derive the EvoTree template from the data definition. ;; evotree-template: EvoTree Any (define (evotree-template t) (cond [(rspecies? t) (rspecies-template t)] [(evoevent? t) (evoevent-template t)])) This is a straightforward implementation based on the data definition. It s also a good strategy to take a complicated problem (dealing with an EvoTree) and decompose it into simpler problems (dealing with a RSpecies or an EvoEvent). Functions for these two data definitions are on the next slide. CS 135 Fall 2018 08: Trees 39

;; rspecies-template: RSpecies Any (define (rspecies-template rs) (... (rspecies-name rs)... (rspecies-endangered rs)... )) ;; evoevent-template: EvoEvent Any (define (evoevent-template ee) (... (evoevent-name ee)... (evoevent-age ee)... (evoevent-left ee)... (evoevent-right ee)... )) CS 135 Fall 2018 08: Trees 40 We know that (evoevent-left ee) and (evoevent-right ee) are EvoTrees, so apply the EvoTree-processing function to them. ;; evoevent-template: EvoEvent Any (define (evoevent-template ee) (... (evoevent-name ee)... (evoevent-age ee)... (evotree-template (evoevent-left ee))... (evotree-template (evoevent-right ee))... )) evoevent-template uses evotree-template and evotree-template uses evoevent-template. This is called mutual recursion. CS 135 Fall 2018 08: Trees 41 A function on EvoTrees This function counts the number of recent species within an evotree. ;; (count-species t): Counts the number of recent species ;; (leaves) in the EvoTree t. ;; count-species: EvoTree Nat (define (count-species t) (cond [(rspecies? t) (count-recent t)] [(evoevent? t) (count-evoevent t)])) (check-expect (count-species animal) 7) (check-expect (count-species human) 1) CS 135 Fall 2018 08: Trees 42

;; count-recent RSpecies Nat (define (count-recent t) 1) ;; count-evoevent EvoEvent Nat (define (count-evoevent t) (+ (count-species (evoevent-left t)) (count-species (evoevent-right t)))) CS 135 Fall 2018 08: Trees 43 Traversing a tree A tree traversal refers to the process of visiting each node in a tree exactly once. The increment example from binary trees is one example of a 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 accumulative recursion. CS 135 Fall 2018 08: Trees 44 ;; list-names EvoTree listof(string) (define (list-names t) (cond [(rspecies? t) (list-rs-names t)] [(evoevent? t) (list-ee-names t)])) ;; list-rs-names RSpecies listof(string) (define (list-rs-names rs) (... (rspecies-name rs)... )) ;; list-ca-names EvoEvent listof(string) (define (list-ee-names ee) (... (evoevent-name ee)... (list-names (evoevent-left ee))... (list-names (evoevent-right ee))... )) CS 135 Fall 2018 08: Trees 45

list-names with an accumulator ;; list-names: EvoTree listof(string) (define (list-names t) (list-names/acc t ())) ;; list-names/acc: EvoTree listof(string) listof(string) (define (list-names/acc t names) (cond [(rspecies? t) (list-rs-names t names)] [(evoevent? t) (list-ee-names t names)])) CS 135 Fall 2018 08: Trees 46 ;; list-rs-names: RSpecies listof(string) listof(string) (define (list-rs-names rs names) (cons (rspecies-name rs) names)) ;; list-ee-names: EvoEvent listof(string) listof(string) (define (list-ee-names ee names) (cons (evoevent-name ee) (list-names/acc (evoevent-left ee) (list-names/acc (evoevent-right ee) names)))) (check-expect (list-names human) ("human")) (check-expect (list-names mammal) ("Mammal" "Primate" "human" "chimp" "rat")) CS 135 Fall 2018 08: Trees 47 Practice problems with EvoTrees Count the number of evolutionary events (internal nodes) with and age less than n. For example, the sample tree has 4 events that are less than 400 million years old. Count the number of evolutionary events that occurred to produce a given recent species. Find the evolutionary path from the root of a (sub)tree and a recent species. For example, the path from animal to rat is (animal vertebrate mammal rat). Modify list-names to produce the names of endangered species. CS 135 Fall 2018 08: Trees 48

Binary expression trees The expression ((2 6) + (5 2))/(5 3) can be represented as a tree: / + - * * 5 3 2 6 5 2 CS 135 Fall 2018 08: Trees 49 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. CS 135 Fall 2018 08: Trees 50 (define-struct binode (op left right)) ;; A Binary arithmetic expression Internal Node (BINode) ;; is a (make-binode (anyof + / ) BinExp BinExp) ;; A binary arithmetic expression (BinExp) is one of: ;; a Num ;; a BINode Some examples of binary arithmetic expressions: 5 (make-binode 2 6) (make-binode + 2 (make-binode 5 3)) CS 135 Fall 2018 08: Trees 51

A more complex example: (make-binode / (make-binode + (make-binode 2 6) (make-binode 5 2)) (make-binode 5 3)) CS 135 Fall 2018 08: Trees 52 Template for binary arithmetic expressions The only new idea in forming the template is the application of the recursive function to each piece that satisfies the data definition. ;; binexp-template: BinExp Any (define (binexp-template ex) (cond [(number? ex)... ex... ] [(binode? ex) (... (binode-op ex)... (binexp-template (binode-left ex))... (binexp-template (binode-right ex))... )])) CS 135 Fall 2018 08: Trees 53 Evaluation of expressions (define (eval ex) (cond [(number? ex) ex] [(symbol=? (binode-op ex) ) ( (eval (binode-left ex)) (eval (binode-right ex)))] [(symbol=? (binode-op ex) +) (+ (eval (binode-left ex)) (eval (binode-right ex)))] [(symbol=? (binode-op ex) /) (/ (eval (binode-left ex)) (eval (binode-right ex)))] [(symbol=? (binode-op ex) ) ( (eval (binode-left ex)) (eval (binode-right ex)))])) CS 135 Fall 2018 08: Trees 54

(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 right) (cond [(symbol=? op ) ( left right)] [(symbol=? op +) (+ left right)] [(symbol=? op /) (/ left right)] [(symbol=? op ) ( left right)])) CS 135 Fall 2018 08: Trees 55 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? CS 135 Fall 2018 08: Trees 56 General arithmetic expressions For binary arithmetic expressions, we formed binary trees. Racket expressions using the functions + and can have an unbounded number of arguments. For simplicity, we will restrict the operations to + and. (+ ( 4 2) 3 (+ 5 1 2) 2) CS 135 Fall 2018 08: Trees 57

We can visualize an arithmetic expression as a general tree. + * 3 + 2 4 2 5 1 2 (+ ( 4 2) 3 (+ 5 1 2) 2) CS 135 Fall 2018 08: Trees 58 For a binary arithmetic expression, we defined a structure with three fields: the operation, the first argument, and the second argument. For a general arithmetic expression, we define a structure with two fields: the operation and a list of arguments (which is a list of arithmetic expressions). CS 135 Fall 2018 08: Trees 59 (define-struct ainode (op args)) ;; a Arithmetic expression Internal Node (AINode) ;; is a (make-ainode (anyof +) (listof AExp)) ;; An Arithmetic Expression (AExp) is one of: ;; a Num ;; an AINode Each definition depends on the other, and each template will depend on the other. We also saw this in the evolution trees example. An EvoTree was defined in terms of RSpecies and EvoEvent. EvoEvent was defined in terms of EvoTree. CS 135 Fall 2018 08: Trees 60

Examples of arithmetic expressions: 3 (make-ainode + (list 3 4)) (make-ainode (list 3 4)) (make-ainode + (list (make-ainode (4 2)) 3 (make-ainode + (5 1 2)) 2)) It is also possible to have an operation and an empty list; recall substitution rules for and and or. CS 135 Fall 2018 08: Trees 61 Templates for arithmetic expressions (define (aexp-template ex) (cond [(number? ex)... ] [(ainode? ex) (... (ainode-template ex)... )])) (define (ainode-template ex) (... (ainode-op ex)... (listof-aexp-template (ainode-args ex))... )) CS 135 Fall 2018 08: Trees 62 ainode-template (define (listof-aexp-template exlist) (cond [(empty? exlist)... ] [else (... (aexp-template (first exlist))... (listof-aexp-template (rest exlist))... )])) We can combine this template with ainode-template in our implementation. CS 135 Fall 2018 08: Trees 63

The function eval ;; eval: AExp Num (define (eval ex) (cond [(number? ex) ex] [else (apply (ainode-op ex) (ainode-args ex))])) CS 135 Fall 2018 08: Trees 64 ;; apply: Sym (listof AExp) Num (define (apply f exlist) (cond [(empty? exlist) (cond [(symbol=? f ) 1] [(symbol=? f +) 0])] [(symbol=? f ) ( (eval (first exlist)) (apply f (rest exlist)))] [(symbol=? f +) (+ (eval (first exlist)) (apply f (rest exlist)))])])) CS 135 Fall 2018 08: Trees 65 A reorganized apply ;; apply: Sym (listof AExp) Num (define (apply f exlist) (cond [(and (empty? exlist) (symbol=? f )) 1] [(and (empty? exlist) (symbol=? f +)) 0] [(symbol=? f ) ( (eval (first exlist)) (apply f (rest exlist)))] [(symbol=? f +) (+ (eval (first exlist)) (apply f (rest exlist)))])) CS 135 Fall 2018 08: Trees 66

Condensed trace of aexp evaluation (eval (make-ainode + (list (make-ainode (3 4)) (make-ainode (2 5))))) (apply + (list (make-ainode (3 4)) (make-ainode (2 5)))) (+ (eval (make-ainode (3 4))) (apply + (list (make-ainode (2 5))))) (+ (apply (3 4)) (apply + (list (make-ainode (2 5))))) CS 135 Fall 2018 08: Trees 67 (+ ( (eval 3) (apply (4))) (apply + (list (make-ainode (2 5))))) (+ ( 3 (apply (4))) (apply + (list (make-ainode (2 5))))) (+ ( 3 ( (eval 4) (apply empty))) (apply + (list (make-ainode (2 5))))) (+ ( 3 ( 4 (apply empty))) (apply + (list (make-ainode (2 5))))) CS 135 Fall 2018 08: Trees 68 (+ ( 3 ( 4 1)) (apply + (list (make-ainode (2 5))))) (+ 12 (apply + (list (make-ainode (2 5))))) (+ 12 (+ (eval (make-ainode (2 5))) (apply + empty))) (+ 12 (+ (apply (2 5)) (apply + empty))) (+ 12 (+ ( (eval 2) (apply (5))) (apply + empty))) CS 135 Fall 2018 08: Trees 69

(+ 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 (+ ( 2 5) (apply + empty))) (+ 12 (+ 10 (apply + empty))) (+ 12 (+ 10 0)) (+ 12 10) 22 CS 135 Fall 2018 08: Trees 70 Alternate data definition In Module 6, we saw how a list could be used instead of a structure holding tax record information. Here we could use a similar idea to replace the structure ainode and the data definitions for AExp. CS 135 Fall 2018 08: Trees 71 ;; 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 of expressions. 3 (+ 3 4) (+ ( 4 2 3) (+ ( 5 1 2) 2)) CS 135 Fall 2018 08: Trees 72

Templates: AltAExp and (listof AltAExp) (define (altaexp-template ex) (cond [(number? ex)... ] [else (... (first ex)... (listof-altaexp-template (rest ex))... )])) (define (listof-altaexp-template exlist) (cond [(empty? exlist)... ] [(cons? exlist) (... (altaexp-template (first exlist))... (listof-altaexp-template (rest exlist))... )])) CS 135 Fall 2018 08: Trees 73 ;; eval: AltAExp Num (define (eval aax) (cond [(number? aax) aax] [else (apply (first aax) (rest aax))])) CS 135 Fall 2018 08: Trees 74 ;; apply: Sym (listof AltAExp) Num (define (apply f aaxl) (cond [(and (empty? aaxl) (symbol=? f )) 1] [(and (empty? aaxl) (symbol=? f +)) 0] [(symbol=? f ) ( (eval (first aaxl)) (apply f (rest aaxl)))] [(symbol=? f +) (+ (eval (first aaxl)) (apply f (rest aaxl)))])) CS 135 Fall 2018 08: Trees 75

A condensed trace (eval ( (+ 1 2) 4)) (apply ((+ 1 2) 4)) ( (eval (+ 1 2)) (apply (4))) ( (apply + (1 2)) (apply (4))) ( (+ 1 (apply + (2))) (apply (4))) ( (+ 1 (+ 2 (apply + ()))) (apply (4))) ( (+ 1 (+ 2 0)) (apply (4))) CS 135 Fall 2018 08: Trees 76 ( (+ 1 2) (apply (4))) ( 3 (apply (4))) ( 3 ( 4 (apply ()))) ( 3 ( 4 1)) ( 3 4) 12 CS 135 Fall 2018 08: Trees 77 Structuring data using mutual recursion Mutual recursion arises when complex relationships among data result in cross references 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. CS 135 Fall 2018 08: Trees 78

Other uses of general trees We can generalize from allowing only two arithmetic operations and numbers to allowing 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 expressions can be applied to tagged hierarchical data, of which a Racket expression is just one example. Organized text and Web pages provide other examples. CS 135 Fall 2018 08: Trees 79 (chapter (section (paragraph "This is the first sentence." "This is the second sentence.") (paragraph "We can continue in this manner.")) (section... )... ) CS 135 Fall 2018 08: Trees 80 (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.)")) CS 135 Fall 2018 08: Trees 81

Nested lists We have discussed flat lists (no nesting): (list a 1 "hello" x) and lists of lists (one level of nesting): (list (list 1 "a") (list 2 "b")) We now consider nested lists (arbitrary nesting): ((1 (2 3)) 4 (5 (6 7 8) 9)) CS 135 Fall 2018 08: Trees 82 Nested lists It is often useful to visualize a nested list as a tree, in which the leaves correspond to the elements of the list, and the internal nodes indicate the nesting: 4 1 5 9 ( ) 2 3 6 7 8 ((1 (2 3)) 4 (5 (6 7 8) 9 ())) CS 135 Fall 2018 08: Trees 83 Examples of nested lists: empty (4 2) ((4 2) 3 (4 1 6)) ((3) 2 () (4 (3 6))) Each nonempty tree is a list of subtrees. The first subtree in the list is either a single leaf (not a list) or a subtree rooted at an internal node (a list). CS 135 Fall 2018 08: Trees 84

Data definition for nested lists ;; A nested list of numbers (Nest-List-Num) is one of: ;; empty ;; (cons Num Nest-List-Num) ;; (cons Nest-List-Num Nest-List-Num) This can be generalized to generic types: (Nest-List-X) CS 135 Fall 2018 08: Trees 85 Template for nested lists The template follows from the data definition. nest-lst-template: Nest-List-Num Any (define (nest-lst-template lst) (cond [(empty? lst)... ] [(number? (first lst)) (... (first lst)... (nest-lst-template (rest lst))... )] [else (... (nest-lst-template (first lst))... (nest-lst-template (rest lst))... )])) CS 135 Fall 2018 08: Trees 86 The function count-items ;; count-items: Nest-List-Num Nat (define (count-items nln) (cond [(empty? nln) 0] [(number? (first nln)) (+ 1 (count-items (rest nln)))] [else (+ (count-items (first nln)) (count-items (rest nln)))])) CS 135 Fall 2018 08: Trees 87

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 CS 135 Fall 2018 08: Trees 88 Flattening a nested list flatten produces a flat list from a nested list. ;; flatten: Nest-List-Num (listof Num) (define (flatten lst)... ) We make use of the built-in Racket function append. (append (1 2) (3 4)) (1 2 3 4) Remember: use append only when the first list has length greater than one, or there are more than two lists. CS 135 Fall 2018 08: Trees 89 ;; flatten: Nest-List-Num (listof Num) (define (flatten lst) (cond [(empty? lst) empty] [(number? (first lst)) (cons (first lst) (flatten (rest lst)))] [else (append (flatten (first lst)) (flatten (rest lst)))])) CS 135 Fall 2018 08: Trees 90

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))) CS 135 Fall 2018 08: Trees 91 Goals of this module You should be familiar with tree terminology. You should understand the data definitions for binary trees, binary search trees, evolutionary trees, and binary arithmetic expressions. You should understand how the templates are derived from those definitions, and how to use the templates to write functions that consume those types of data. You should understand the definition of a binary search tree and its ordering property. CS 135 Fall 2018 08: Trees 92 You should be able to write functions which consume binary search trees, including those sketched (but not developed fully) in lecture. You should be able to develop and use templates for other binary trees, not necessarily presented in lecture. You should understand the idea of mutual recursion for both examples given in lecture and new ones that might be introduced in lab, assignments, or exams. You should be able to develop templates from mutually recursive data definitions, and to write functions using the templates. CS 135 Fall 2018 08: Trees 93