CS61A Lecture 12 Immutable Trees Jom Magrotker UC Berkeley EECS July 9, 2012.

Slides:



Advertisements
Similar presentations
CS61A Lecture 25 Delayed Sequences Jom Magrotker UC Berkeley EECS July 31, 2012.
Advertisements

CS61A Lecture 8 Data Abstraction Tom Magrino and Jon Kotker UC Berkeley EECS June 28, 2012.
Chapter 4: Trees Part II - AVL Tree
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
CS 206 Introduction to Computer Science II 09 / 24 / 2008 Instructor: Michael Eckmann.
They’re not just binary anymore!
BST Data Structure A BST node contains: A BST contains
Binary Search Introduction to Trees. Binary searching & introduction to trees 2 CMPS 12B, UC Santa Cruz Last time: recursion In the last lecture, we learned.
B + -Trees (Part 1) Lecture 20 COMP171 Fall 2006.
B + -Trees (Part 1). Motivation AVL tree with N nodes is an excellent data structure for searching, indexing, etc. –The Big-Oh analysis shows most operations.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Data Structures Using C++ 2E Chapter 11 Binary Trees and B-Trees.
1 Section 9.2 Tree Applications. 2 Binary Search Trees Goal is implementation of an efficient searching algorithm Binary Search Tree: –binary tree in.
1 Joe Meehean.  Important and common problem  Given a collection, determine whether value v is a member  Common variation given a collection of unique.
Binary Search Trees Section Trees Trees are efficient Many algorithms can be performed on trees in O(log n) time. Searching for elements.
Data Structures Using C++1 Chapter 11 Binary Trees.
CS61A Lecture 14 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 11, 2012.
B-Tree. B-Trees a specialized multi-way tree designed especially for use on disk In a B-tree each node may contain a large number of keys. The number.
Trees Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
B-trees (Balanced Trees) A B-tree is a special kind of tree, similar to a binary tree. However, It is not a binary search tree. It is not a binary tree.
More Trees Multiway Trees and 2-4 Trees. Motivation of Multi-way Trees Main memory vs. disk ◦ Assumptions so far: ◦ We have assumed that we can store.
Chapter 19: Binary Trees. Objectives In this chapter, you will: – Learn about binary trees – Explore various binary tree traversal algorithms – Organize.
Trees. Introduction to Trees Trees are very common in computer science They come in different forms They are used as data representation in many applications.
CS61A Lecture 21 Scheme Jom Magrotker UC Berkeley EECS July 24, 2012.
CS61A Lecture 16 Mutable Data Structures Jom Magrotker UC Berkeley EECS July 16, 2012.
S EARCHING AND T REES COMP1927 Computing 15s1 Sedgewick Chapters 5, 12.
CS61A Lecture 15 Object-Oriented Programming, Mutable Data Structures Jom Magrotker UC Berkeley EECS July 12, 2012.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
INTRODUCTION TO BINARY TREES P SORTING  Review of Linear Search: –again, begin with first element and search through list until finding element,
CS61A Lecture 22 Interpretation Jom Magrotker UC Berkeley EECS July 25, 2012.
CS61A Lecture 6 Recursion Tom Magrino and Jon Kotker UC Berkeley EECS June 26, 2012.
CS61A Lecture 13 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 10, 2012.
Tree (new ADT) Terminology:  A tree is a collection of elements (nodes)  Each node may have 0 or more successors (called children)  How many does a.
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
1 Binary Trees Informal defn: each node has 0, 1, or 2 children Informal defn: each node has 0, 1, or 2 children Formal defn: a binary tree is a structure.
TREES Lecture 12 CS2110 – Fall Announcements  Prelim #1 is tonight!  Olin 155  A-L  5:30  M-Z  5:30  A4 will be posted today  Mid-semester.
Even MORE Balanced Trees Computing 2 COMP s1.
CS61A Lecture 27 Logic Programming Jom Magrotker UC Berkeley EECS August 2, 2012.
CS61A Lecture 20 Object-Oriented Programming: Implementation Jom Magrotker UC Berkeley EECS July 23, 2012.
H EAPS. T WO KINDS OF HEAPS : MAX AND MIN Max: Every child is smaller than its parent Meaning the max is the root of the tree 10 / \ 9 7 / \ 6 8 / \ 2.
CIS 068 Welcome to CIS 068 ! Lesson 12: Data Structures 3 Trees.
TREES K. Birman’s and G. Bebis’s Slides. Tree Overview 2  Tree: recursive data structure (similar to list)  Each cell may have zero or more successors.
CS61A Lecture 9 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 2, 2012.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
Week 7 - Wednesday.  What did we talk about last time?  Recursive running time  Master Theorem  Symbol tables.
CS61A Lecture 10 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 3, 2012.
CS61A Lecture 11 Immutable Trees Jom Magrotker UC Berkeley EECS July 5, 2012.
Trees Chapter 15.
Data Structure and Algorithms
Binary Search Trees A binary search tree is a binary tree
B+-Trees.
B+-Trees.
ITEC 2620M Introduction to Data Structures
Binary Trees, Binary Search Trees
Chapter 20: Binary Trees.
Chapter 21: Binary Trees.
Balanced-Trees This presentation shows you the potential problem of unbalanced tree and show two way to fix it This lecture introduces heaps, which are.
Find in a linked list? first last 7  4  3  8 NULL
Tree A tree is a data structure in which each node is comprised of some data as well as node pointers to child nodes
B-Trees This presentation shows you the potential problem of unbalanced tree and show one way to fix it This lecture introduces heaps, which are used.
Balanced-Trees This presentation shows you the potential problem of unbalanced tree and show two way to fix it This lecture introduces heaps, which are.
Binary Trees, Binary Search Trees
CSC 143 Java Trees.
Chapter 20: Binary Trees.
B-Trees This presentation shows you the potential problem of unbalanced tree and show one way to fix it This lecture introduces heaps, which are used.
Instructor: Dr. Michael Geiger Spring 2019 Lecture 34: Exam 3 Preview
Binary Trees, Binary Search Trees
Data Structures Using C++ 2E
Analysis of Algorithms CS 477/677
Presentation transcript:

CS61A Lecture 12 Immutable Trees Jom Magrotker UC Berkeley EECS July 9, 2012

2 C OMPUTER S CIENCE IN THE N EWS

3 T ODAY Review: Immutable Trees Binary Trees and Binary Search Trees Extra: Tuples versus IRLists

4 R EVIEW : H IERARCHICAL D ATA Often, we find that information is nicely organized into hierarchies. Example: Writing! Book Chapter Paragraph Sentence Word

5 R EVIEW : T REES A tree data structure traditionally has two parts: 1.A datum: Information stored at the top. 2.Some children: Trees that appear below this tree. Children Datum

6 R EVIEW : T REES Notice that trees are also recursively defined. A tree is made from other trees – these trees are its subtrees.

7 R EVIEW : T REES B B C C Nodes Branches A is a parent to B and C B and C are children of A A A

8 R EVIEW : T REES fib(4) fib(3) fib(2) fib(1) fib(0) fib(2) fib(1) fib(0) fib(1) Root Leaves

9 R EVIEW : I MMUTABLE T REES make_itree(1, (make_itree(2), make_itree(3, (make_itree(4), make_itree(5))), make_itree(6, (make_itree(7),)))) Root Tuple of children (each is an ITree!) Tuple of children (each is an ITree!) No children Only one child

10 R EVIEW : I MMUTABLE T REES itree_datum(fir) is 1 itree_children(fir) is the tuple fir = 2 2 (, , ) This is not what is printed! The expression evaluates to a tuple of ITrees, which are the children of fir. This is not what is printed! The expression evaluates to a tuple of ITrees, which are the children of fir. A group of trees is called a forest.

11 R EVIEW : IT REES def make_itree(datum, children=()): return (datum, children) def itree_datum(t): return t[0] def itree_children(t): return t[1] C ONSTRUCTOR S ELECTORS

12 R EVIEW : O PERATING ON IT REES Write the function itree_prod, which takes an ITree of numbers and returns the product of all the numbers in the ITree. >>> t = make_itree(1, (make_itree(2), make_itree(3), make_itree(4))) >>> itree_prod(t) 24

13 E XAMPLE : O PERATING ON IT REES Idea: Split the problem into two different parts: one that handles a single tree and one that handles a forest. def itree_prod(t): return itree_datum(t) * forest_prod(itree_children(t)) def forest_prod(f): if len(f) == 0: return 1 return itree_prod(f[0]) * forest_prod(f[1:]) Returns the product of numbers in an ITree. Datum, multiplied by… … the product of all the numbers in all the ITrees in the forest. These ITrees are the children. Product of numbers in the first ITree, multiplied by… … the product of all the numbers in all the other ITrees of the forest.

14 E XAMPLE : O PERATING ON IT REES Idea: Split the problem into two different parts: one that handles a single tree and one that handles a forest. def itree_prod(t): return itree_datum(t) * forest_prod(itree_children(t)) def forest_prod(f): if len(f) == 0: return 1 return itree_prod(f[0]) * forest_prod(f[1:]) Not a data abstraction violation. We know that f is a tuple of ITrees. Not a data abstraction violation. We know that f is a tuple of ITrees.

15 E XAMPLE : O PERATING ON IT REES Idea: Split the problem into two different parts: one that handles a single tree and one that handles a forest. def itree_prod(t): return itree_datum(t) * forest_prod(itree_children(t)) def forest_prod(f): if len(f) == 0: return 1 return itree_prod(f[0]) * forest_prod(f[1:]) This is called mutual recursion because it involves two functions recursively calling each other!

16 M UTUAL R ECURSION To find the product of the whole ITree in itree_prod, we need to apply itree_prod itself to the smaller subtrees that are the children of the provided itree. forest_prod does this for us.

17 E XAMPLE : O PERATING ON IT REES An alternate definition for itree_prod does not need two separate and smaller functions: from operator import mul def itree_prod(t): return itree_datum(t) * \ reduce(mul, map(itree_prod, itree_children(t)), 1) Multiplies all the results of applying itree_prod on the children. Applies itree_prod recursively on the children.

18 P RACTICE : O PERATING ON IT REES Write a function scale_itree that takes an ITree of numbers and a scaling factor, and returns a new ITree that results from scaling each number in the original ITree scale_itree, 2=

19 P RACTICE : O PERATING ON IT REES def scale_itree(itree, factor): return make_itree(___________________________, scale_forest(_____________________, ______)) def scale_forest(forest, factor): results = () for itree in forest: results = results + __________________________ return results

20 P RACTICE : O PERATING ON IT REES def scale_itree(itree, factor): return make_itree(itree_datum(itree) * factor, scale_forest(itree_children(itree), factor)) def scale_forest(forest, factor): results = () for itree in forest: results = results + scale_itree(itree, factor) return results

21 P RACTICE : O PERATING ON IT REES Alternative solution: def scale_itree(itree, factor): return make_itree(itree_datum(itree) * factor, scale_forest(itree_children(itree), factor)) def scale_forest(forest, factor): if len(forest) == 0: return () return (scale_itree(forest[0], factor),) + \ scale_forest(forest[1:], factor) Tuple of one tree

22 P RACTICE : O PERATING ON IT REES def scale_itree(itree, factor): return make_itree(___________________________, tuple(map(__________, _____________________)))

23 P RACTICE : O PERATING ON IT REES def scale_itree(itree, factor): return make_itree(itree_datum(itree) * factor, tuple(map(scale_itree, itree_children(itree))))

24 P RACTICE : O PERATING ON IT REES Write a function count_leaves that counts the number of leaves in the ITree provided count_leaves 4=

25 P RACTICE : O PERATING ON IT REES def count_leaves(itree): if ______________: return 1 return cl_forest(_____________________) def cl_forest(f): if len(f) == 0: return _ return _____________________________________

26 P RACTICE : O PERATING ON IT REES def count_leaves(itree): if is_leaf(itree): return 1 return cl_forest(itree_children(itree)) def cl_forest(f): if len(f) == 0: return 0 return count_leaves(f[0]) + cl_forest(f[1:]) def is_leaf(itree): return len(itree_children(itree)) == 0

27 P RACTICE : O PERATING ON IT REES def count_leaves(itree): if ______________: return 1 return reduce(___, map(____________, _____________________), _)

28 P RACTICE : O PERATING ON IT REES def count_leaves(itree): if is_leaf(itree): return 1 return reduce(add, map(count_leaves, itree_children(itree)), 0)

29 A NNOUNCEMENTS Homework 6 is due tomorrow, July 10. – Starting with the next homework, we will mark questions as core and reinforcement. – The core questions are ones that we suggest you work on to understand the idea better. – The reinforcement questions are extra problems that you can practice with, but are not as critical. Project 2 is due on Friday, July 13. Homework 0 for the staff is now available.

30 A NNOUNCEMENTS Midterm 1 is tonight. – Where? 2050 VLSB. – When? 7PM to 9PM. Closed book and closed electronic devices. One 8.5” x 11” ‘cheat sheet’ allowed. Group portion is 15 minutes long. Post-midterm potluck on Wednesday, July 11 in the Wozniak Lounge from 6:30pm to 10pm. – Bring food, drinks and board games! – Drop by if and when you can.

31 A NNOUNCEMENTS C AMPANILE

32 B REAK

33 P ROBLEM S OLVING : S EARCHING Searching is a problem that shows up frequently in many different (and daily!) settings. Problem: We have a collection of data and we need to find a certain datum. Examples: Searching for a person in a phone book. Searching for a webpage on the Internet. … and so on.

34 P ROBLEM S OLVING : S EARCHING Write a predicate function has_num that determines if a number is in a tuple of numbers. def has_num(tup, num_to_find): for item in tup: if ___________: return ____ return _____

35 P ROBLEM S OLVING : S EARCHING Write a predicate function has_num that determines if a number is in a tuple of numbers. def has_num(tup, num_to_find): for item in tup: if item == num: return True return False

36 P ROBLEM S OLVING : S EARCHING

37 T REES IN R EAL L IFE : B INARY T REES Trees where each node has at most two children are known as binary trees

38 T REES IN R EAL L IFE : B INARY S EARCH T REES Binary search trees are binary trees where all of the items to the left of a node are smaller, and the items to the right are larger How? Why the term “search trees”? They speed up the search for an item in a sequence. Why the term “search trees”? They speed up the search for an item in a sequence.

39 T REES IN R EAL L IFE : B INARY S EARCH T REES Let us try to find 4 in this binary search tree: It could be anywhere here

40 T REES IN R EAL L IFE : B INARY S EARCH T REES Let us try to find 4 in this binary search tree: It could be anywhere here. Discard this half of the data. It can’t be here! They’re too big. Discard this half of the data. It can’t be here! They’re too big

41 T REES IN R EAL L IFE : B INARY S EARCH T REES Let us try to find 4 in this binary search tree: It is present in the BST

42 T REES IN R EAL L IFE : B INARY S EARCH T REES Let us try to find 1 4 in this binary search tree: It could be anywhere here

43 T REES IN R EAL L IFE : B INARY S EARCH T REES Let us try to find 1 4 in this binary search tree: It could be anywhere here. Discard this half of the data. It can’t be here! They’re too small. Discard this half of the data. It can’t be here! They’re too small

44 T REES IN R EAL L IFE : B INARY S EARCH T REES Let us try to find 1 4 in this binary search tree: It could be anywhere here

45 T REES IN R EAL L IFE : B INARY S EARCH T REES Let us try to find 1 4 in this binary search tree: It is present in the BST

46 T REES IN R EAL L IFE : B INARY S EARCH T REES Let us try to find 1 1 in this binary search tree: It could be anywhere here

47 T REES IN R EAL L IFE : B INARY S EARCH T REES Let us try to find 1 1 in this binary search tree: It could be anywhere here. Discard this half of the data. It can’t be here! They’re too small. Discard this half of the data. It can’t be here! They’re too small

48 T REES IN R EAL L IFE : B INARY S EARCH T REES Let us try to find 1 1 in this binary search tree: Discard this half of the data. It can’t be here! They’re too big. Discard this half of the data. It can’t be here! They’re too big

49 T REES IN R EAL L IFE : B INARY S EARCH T REES Let us try to find 1 1 in this binary search tree: It isn’t present in the BST. 

50 T REES IN R EAL L IFE : B INARY S EARCH T REES Two important things when searching for an item in a binary search tree (BST): 1.As we go down the tree, from one level to another, from parent to child, we discard approximately half the data each time. 2.In the worst case, we go down all the way to the leaves.

51 T REES IN R EAL L IFE : B INARY S EARCH T REES Approximately as many nodes on the left of any node as there are on the right of that node.

52 L OGARITHMIC A LGORITHM …

53 L OGARITHMIC A LGORITHM

54 L OGARITHMIC A LGORITHM

55 T REES IN R EAL L IFE : B INARY S EARCH T REES

56 BST ADT empty_bst = None def make_bst(datum, left=empty_bst, right=empty_bst): return (left, datum, right) def bst_datum(b): return b[1] def bst_left(b): return b[0] def bst_right(b): return b[2] C ONSTRUCTOR S ELECTORS

57 BST ADT bst_is_leaf(b) returns True if the BST is a leaf: def bst_is_leaf(b): return bst_left(b) == empty_bst and bst_right(b) == empty_bst

58 BST ADT def has_num(b, num): if b == empty_bst: return False elif bst_datum(b) == item: return ____ elif bst_datum(b) > item: return has_num(___________, num) return has_num(____________, num)

59 BST ADT def has_num(b, num): if b == empty_bst: return False elif bst_datum(b) == item: return True elif bst_datum(b) > item: return has_num(bst_left(b), num) return has_num(bst_right(b), num)

60 C ONCLUSION ITrees are useful for representing general tree- structures. Binary search trees allow us to search through data faster. Preview: Object-oriented programming: a brand new paradigm.

61 G OOD L UCK T ONIGHT !

62 E XTRA : T UPLES VERSUS IRL ISTS Tuples and IRLists are two different ways of representing lists of items: they are two different data structures, each with their own advantages and disadvantages. You will compare them further in CS61B, but here is a preview.

63 E XTRA : T UPLES VERSUS IRL ISTS IRLists are recursively defined, tuples are not. This gives IRLists an advantage when you want to perform a naturally recursive task, such as mapping a function on a sequence.

64 E XTRA : T UPLES VERSUS IRL ISTS Which of the following methods is better? def map_irlist(fn, irl): return make_irlist(fn(irlist_first(irl)), map_irlist(fn, irlist_rest(irl))) def map_tuple(fn, tup): results = () for item in tup: results = results + (fn(item),) return results

65 E XTRA : T UPLES VERSUS IRL ISTS map_irlist is better than map_tuple. map_tuple creates and discards temporary tuples, since tuples are immutable. map_irlist “tacks on” new items to the front of an existing (and growing) IRList.

66 E XTRA : T UPLES VERSUS IRL ISTS Tuples are unchanging sequences of data, which gives them an advantage when all you want to do is grab information from a sequence.

67 E XTRA : T UPLES VERSUS IRL ISTS Which of the following methods is better? def getitem_tuple(tup, pos): return tup[pos] def getitem_irlist(irl, pos): if pos == 0: return irlist_first(irl) return getitem_irlist(irlist_rest(irl), pos-1)

68 E XTRA : T UPLES VERSUS IRL ISTS getitem_tuple is better than getitem_irlist. Indexing into a tuple takes (on average) constant time, but indexing into an IRList takes linear time.