Compsci 201 201 Sear earch T Tree ees an and Recursio sion - - PowerPoint PPT Presentation

compsci 201 201 sear earch t tree ees an and recursio sion
SMART_READER_LITE
LIVE PREVIEW

Compsci 201 201 Sear earch T Tree ees an and Recursio sion - - PowerPoint PPT Presentation

Compsci 201 201 Sear earch T Tree ees an and Recursio sion Susan Rodger March 6, 2020 3/6/2020 Compsci 201, Spring 2020 1 P is for Patterns Object-oriented design: from decorator to Password From changeme to oh-oh


slide-1
SLIDE 1

Compsci 201 201 Sear earch T Tree ees an and Recursio sion

3/6/2020 Compsci 201, Spring 2020 1

Susan Rodger March 6, 2020

slide-2
SLIDE 2

P is for …

  • Patterns
  • Object-oriented design: from decorator to …
  • Password
  • From changeme to oh-oh
  • Phishing
  • From changeme to bitcoin!

3/6/2020 Compsci 201, Spring 2020 2

slide-3
SLIDE 3

Announcements

  • Assig

ignm nment nt P P4 DNA-Link ink

  • Part 1 due yesterday! – Analysis, Partner form
  • Part 2 due March 19 – Code and more Analysis
  • Ther

There is is Discus cussio ion f n for M Monday, M , March 1 h 16

  • There is no Pre-Discussion before
  • APT

APT-5 o

  • ut

ut af after b brea eak

3/6/2020 Compsci 201, Spring 2020 3

slide-4
SLIDE 4

Plan for DBSB

  • Bina

inary T Tree ees

  • Search and more: best of array and linked lists
  • O(1) insert and O(log n) search
  • Understanding structure and recursion
  • List has one node and another list
  • Tree has one node/root and two subtrees
  • Compar

aring ing t two object cts

3/6/2020 Compsci 201, Spring 2020 4

slide-5
SLIDE 5

Binary Search Trees

  • Nodes h

have l e left/r /rig ight ht r refer erenc ences: s similar ilar prev rev/ne /next

  • At each node: <= goes left, > goes right
  • How d

do w we search? h?

  • How d

do w we e ins insert?

  • Insert: “

“koala” la”

“llama” “tiger”

“monkey” “jaguar” “elephant”

“giraffe” “pig” “hippo”

“leopard” 3/6/2020 Compsci 201, Spring 2020 5

slide-6
SLIDE 6

“koala”

Binary Search Trees

  • Nodes h

have l e left/r /rig ight ht r refer erenc ences: s similar ilar prev rev/ne /next

  • At each node: <= goes left, > goes right
  • How d

do w we search? h?

  • How d

do w we e ins insert?

  • Insert: “

“koala” la”

“llama” “tiger”

“monkey” “jaguar” “elephant”

“giraffe” “pig” “hippo”

“leopard”

“koala” “koala” “koala” “koala”

3/6/2020 Compsci 201, Spring 2020 6

“koala”

slide-7
SLIDE 7

Tree Terminology

  • Root: "

"top n node", h has s no parent

  • "macaque". Subtrees also have a root
  • Leaf

af: : bottom n nodes es, h have n no childr dren en

  • "baboon", "lemur", "organutan"
  • Pat

ath: s : sequen ence ce of p paren rent-ch child n d nodes es

  • "macaque", "chimp", "lemur"

3/6/2020 Compsci 201, Spring 2020 7

slide-8
SLIDE 8

A TreeNode by any other name…

  • Wha

hat does es t thi his lo look lik like? D Doub ubly link linked lis list?

public class TreeNode { TreeNode left; TreeNode right; String info; TreeNode(String s, TreeNode llink, TreeNode rlink){ info = s; left = llink; right = rlink; } }

“llama” “tiger” “giraffe”

3/6/2020 Compsci 201, Spring 2020 8

slide-9
SLIDE 9

Trees: Concepts and Code

  • In a sear

arch t ch tree ee: : proper erty h holds a at e ever ery n node

  • Nodes in left subtree are < (or <=)
  • Nodes in right subtree are >
  • To sea

earch o

  • r ad

add: if if no not f found und?

  • Look left if <=
  • Look right if >
  • Iterative or recursive

3/6/2020 Compsci 201, Spring 2020 9

slide-10
SLIDE 10

Tree Performance

  • Sea

earch f for any any val

  • alue. C

Compare t to root and and …

  • Similar

ilar t to binar ary s sear arch.

  • ch. O(log N) if

if tree ee "g "good"

  • Trees are generally well-behaved, but !!!
  • Guarantee? Balanced tree: AVL or Red-Black
  • We

e get O O(lo log N N) sea earch and and … …

  • No shifting to add, find leaf

3/6/2020 Compsci 201, Spring 2020 10

slide-11
SLIDE 11

Good Search Trees and Bad Trees

http://www.9wy.net/onlinebook/CPrimerPlus5/ch17lev1sec7.html

3/6/2020 Compsci 201, Spring 2020 11

slide-12
SLIDE 12

Printing a Search Tree

  • Think

nk o

  • f sear

arch t ch trees ees as as recur cursiv ive/hier /hierar archical chical

  • Empty OR Root/Node with two subtrees
  • What do we know about subtrees? Also tree!

3/6/2020 Compsci 201, Spring 2020 12

slide-13
SLIDE 13

Print the tree - Recursion

3/6/2020 Compsci 201, Spring 2020 13

slide-14
SLIDE 14

Print the tree - Recursion

3/6/2020 Compsci 201, Spring 2020 14

1

1

baboon chimp lemur OUTPUT:

Believe in recursion

slide-15
SLIDE 15

Print the tree - Recursion

3/6/2020 Compsci 201, Spring 2020 15

2

2

OUTPUT: baboon chimp lemur macaque

slide-16
SLIDE 16

Print the tree - Recursion

3/6/2020 Compsci 201, Spring 2020 16

3

3

OUTPUT: baboon chimp lemur macaque monkey orangutan tamarin

Believe in recursion

slide-17
SLIDE 17

Print the tree - Recursion

3/6/2020 Compsci 201, Spring 2020 17

1 2 3

1 3 2

slide-18
SLIDE 18

If you don’t believe in recursion yet, let’s see all the steps.

3/6/2020 Compsci 201, Spring 2020 18

A green check mark will mean we have finished all the recursion for a node.

slide-19
SLIDE 19

Print the tree - Recursion

3/6/2020 Compsci 201, Spring 2020 19

OUTPUT:

slide-20
SLIDE 20

Print the tree - Recursion

3/6/2020 Compsci 201, Spring 2020 45

OUTPUT: baboon chimp lemur macaque monkey orangutan tamarin

slide-21
SLIDE 21

Print the tree - Recursion

3/6/2020 Compsci 201, Spring 2020 46

1 2 3

1 3 2

slide-22
SLIDE 22

Constructing and Printing Tree

  • Code

de a and d visuali ualize: constru ructor h r has 3 3 parame meters rs

  • Info, Left Subtree, Right Subtree

3/6/2020 Compsci 201, Spring 2020 47

slide-23
SLIDE 23

Just larger – PrintTree.java

https://coursework.cs.duke.edu/201spring20/classcode

3/6/2020 Compsci 201, Spring 2020 48

slide-24
SLIDE 24

Visualize

  • A differ

erent ent t tree:

  • Left subtree?
  • Right subtree?

3/6/2020 Compsci 201, Spring 2020 49

slide-25
SLIDE 25

Three recursive calls

3/6/2020 Compsci 201, Spring 2020 50

  • "appl

pple" n node de

  • null,null
  • Up to "

"durian" ian"

slide-26
SLIDE 26

Standard Tree Traversals

  • Pre

re-, I , In-, and and P Post- ord rder

  • When is root visited? Before, in-between, after
  • Analogy: t

: traveling eling t the b border er: d down, u under er, u , up

  • https://coursework.cs.duke.edu/201spring20/classcode
  • See TreeDemo.java, alphabetical for search tree

3/6/2020 Compsci 201, Spring 2020 51

slide-27
SLIDE 27

Inor

  • rder

der traversal – the print nt we just did

  • Analogy: t

: traveling eling t the b border er: und under a a no node

  • Useful to print the elements in order

baboon, , chimp mp, l lemu mur, , macaqu aque, m , monkey, o , orangutan an, , tamari rin

3/6/2020 Compsci 201, Spring 2020 52

slide-28
SLIDE 28

Preor eorder der traversal

  • Analogy: t

: traveling eling t the b border er: o

  • n the w

e way d down

  • Useful to read and write trees: Huffman

macaque, c chimp, b baboon, l lemur, monkey, t tamarin, ora rangutan

3/6/2020 Compsci 201, Spring 2020 54

slide-29
SLIDE 29

Postorder der traversal

  • Analogy: t

: traveling eling t the b border er: o

  • n the w

e way u up

  • Useful to destroy/delete trees

baboon, l lemur, c chimp, ora rangutan, t tamarin, monkey, m macaque

3/6/2020 Compsci 201, Spring 2020 56

slide-30
SLIDE 30

Motivation for Trees

  • Has

ashS hSet and H Has ashM hMap ap a are O O(1) a aver erage

  • Astonishing! Search, insert, delete
  • No order for keys, sometimes order matters
  • Worst-case? Everything in same locker/bucket
  • Just in case? Use a tree in that locker/bucket
  • Sear

arch ch T Trees ees: Tre reeSet et and nd TreeM eMap ap

  • O(log N) no matter what, average and worst
  • "Alphabetical" order and range queries
  • Find all keys in range [low,high] efficiently

3/6/2020 Compsci 201, Spring 2020 58

slide-31
SLIDE 31

Why Trees are O(log N)

  • Wit

ith eac each q quer uery: elim eliminate half half o

  • f tree
  • 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1
  • Can e

n ensur ure t e trees es a are b balanc anced ed: : TreeS eSet/TreeM eMap ap

  • Re-balance on add or delete

3/6/2020 Compsci 201, Spring 2020 59

slide-32
SLIDE 32

WOTO

http://b ://bit.l .ly/20 /201s 1spring2 g20-030 306-1

3/6/2020 Compsci 201, Spring 2020 60

slide-33
SLIDE 33

Richard Stallman

  • Created "

"free" ee" s software f foundation

  • Speech not beer
  • Wrote Gnu C compiler
  • No Linux without gcc
  • MacArthur award, Hopper award
  • Maybe w

world's b best p pro rogra rammer? mmer?

3/6/2020 Compsci 201, Spring 2020 61

You and I we exist for ourselves, fundamentally. We should care about others but each human being is a source of value, each human being deserves things. And so if you lose control

  • ver your computing, that's bad for you, directly bad for you.

So my first reaction is to say: Oh, what a shame; I hope you recover the control over your computing and the way you do that is to stop using the non-free software.

slide-34
SLIDE 34

Not Everything is Comparable

3/6/2020 Compsci 201, Spring 2020 62

slide-35
SLIDE 35

Java-isms for comparing

  • We can c

n compare e int int, d doub uble le, cha char

  • Using ==, and !=, and <, <=, >, >=
  • Primitives use conventional symbols
  • Canno

nnot write " e "apple" le" < < "zeb ebra" a"

  • Must compare objects using specific method
  • Objects must be compar

arable le, that is they must implement the Comparab able le interface

3/6/2020 Compsci 201, Spring 2020 63

slide-36
SLIDE 36

Strings are Comparable

  • Compar

are s e string ngs l lexico cograp aphi hical ally, n nat atural al o

  • rder

ering ng, dict ctionar ary o

  • rder

er

  • “zebra” > “aardvark” but “Zebra” < “aardvark”
  • Conceptual, cannot use < or > or ==
  • We had to use s.equals(t) for strings/objects
  • "yak".compareTo(s) returns < 0, =

== 0, > > 0

  • s is “zebra”, “yak”, and “toad”, respectively
  • The

he in int conv nven ention a n also u used ed in C C++, C C, other hers

3/6/2020 Compsci 201, Spring 2020 64

slide-37
SLIDE 37

Comparable in Java?

  • String

ing i implement nts C Compar arab able le<String ing>

"hello".compareTo("goodbye")

  • Integer i

implement nts C Comparab able< le<Int nteg eger>

new Integer(5).compareTo(new Integer(6))

  • Canno

nnot c compar are e Ar ArrayLists or a r arr rrays

  • Note: .equals works for ArrayList, not arrays

3/6/2020 Compsci 201, Spring 2020 65

slide-38
SLIDE 38

Don't do this at home: (x,y) < (z,w)

  • Can

an w we e compare P Point int objec ects?

  • http://stackoverflow.com/questions/5178092/so

rting-a-list-of-points-with-java

  • Let's lo

look a at t the he Java co code t tha hat m mak akes a a Point int compar arable le t to another her Point

  • Point implements Comparable<Point>
  • public int compareTo(Point other)

3/6/2020 Compsci 201, Spring 2020 67

slide-39
SLIDE 39

Build on What You Know

  • How does .equals

uals w work?

  • Make sure you have the correct type
  • Cast, compare

3/6/2020 Compsci 201, Spring 2020 68

public boolean equals(Object o) { if (o == null || ! (o instanceof Point)) { return false; } Point p = (Point) o; return p.x == x && p.y == y; }

slide-40
SLIDE 40

Extend what you know

  • This

This is is m method in in Poin int c cla lass Point implements Comparable<Point> Note: parameter is Point and and no not Object

3/6/2020 Compsci 201, Spring 2020 69

public int compareTo(Point p) { if (this.x < p.x) return -1; if (this.x > p.x) return 1; // what must be true here? if (this.y < p.y) return -1; if (this.y > p.y) return 1 return 0; }

slide-41
SLIDE 41

Useful math trick: Faster? Care?

  • Use s

subtrac actio ion t n to help w with r h retur urn v n values ues

http://stackoverflow.com/questions/26 265483 839/ 9/rounding-a-do doubl ble-to to-tur turn-it it-into to-an- int nt-jav ava

public int compareTo(Point p) { int deltaX = (int) Math.round(x – p.x); int deltaY = (int) Math.round(y – p.y); if (deltaX == 0) return deltaY; return deltaX; }

3/6/2020 Compsci 201, Spring 2020 71

slide-42
SLIDE 42

Comparable Elements

  • TreeSet<String>,

TreeMap<String,Anything>

  • Tree elements must be comparable
  • Must implement Comparable<..>
  • It's possible to supply a Comparator, later
  • Arrays.sort,

, Collections.sort

  • What algorithm is used in sorting?
  • Can change order of sort: Comparator, later

3/6/2020 Compsci 201, Spring 2020 72

slide-43
SLIDE 43

CompPoint.java in Action

  • https://co

://coursework rk.cs cs.d .duke.ed edu/2 /201spr pring20/c /classco code de

  • We

e can an s sort colle llection o

  • f CompPoint

int objects, ts, what's p t's printed?

  • What if we change the .compareTo method?

3/6/2020 Compsci 201, Spring 2020 73

slide-44
SLIDE 44

WOTO

http://b ://bit.l .ly/20 /201s 1spring2 g20-030 306-2

3/6/2020 Compsci 201, Spring 2020 74

slide-45
SLIDE 45

Jan Cuny

3/6/2020 Compsci 201, Spring 2020 75

Program officer at National Science Foundation (NSF) Leading #CSforAll initiatives. 2009 ABI Woman of Vision Award for Social Impact, 2016 Distinguished Educator Award

“All o l of to today’s k kids ds w will n ll need d – along ng w with r h read ading, writi ting, and a d arith ithme metic tic – a basic ic u unde dersta tandin ding o

  • f

compu mputa tati tion a and d the r role le i it plays a across a wide de rang nge o e of disci ciplines nes.”