Lecture Notes on Tries

Size: px
Start display at page:

Download "Lecture Notes on Tries"

Transcription

1 Lecture Notes on Tries : Principles of Imperative Computation Thomas Cortina, Frank Pfenning, Rob Simmons, Penny Anderson Lecture 22 June 20, Introduction In the data structures implementing associative arrays so far, we have needed either an equality operation and a hash function, or a comparison operator with a total order on keys. Similarly, our sorting algorithms just used a total order on keys and worked by comparisons of keys. We obtain a different class of representations and algorithms if we analyze the structure of keys and decompose them. In this lecture we explore tries, an example from this class of data structures. The asymptotic complexity we obtain has a different nature from data structures based on comparisons, depending on the structure of the key rather than the number of elements stored in the data structure. 2 The Boggle Word Game The Boggle word game is played on an n n grid (usually 4 4 or 5 5). We have n n dice that have letters on all 6 sides and which are shaken so that they randomly settle into the grid. At that point we have an n n grid filled with letters. Now the goal is to find as many words as possible in this grid within a specified time limit. To construct a word we can start at an arbitrary position and use any of the 8 adjacent letters as the second letter. From there we can again pick any adjacent letter as the third letter in the word, and so on. We may not reuse any particular place in the grid in the same word, but they may be in common for different words. For example,

2 Tries L22.2 in the grid E F R A H G D R P S N A E E B E we have the words SEE, SEEP, and BEARDS, but not SEES. Scoring assigns points according to the lengths of the words found, where longer words score higher. One simple possibility for implementing this game is to systematically search for potential words and then look them up in a dictionary, perhaps stored as a sorted word list, some kind of binary search tree, or a hash table. The problem is that there are too many potential words on the grid, so we want to consider prefixes and abort the search when a prefix does not start a word. For example, if we start in the upper right-hand corner and try horizontally first, then EF is a prefix for a number of words, but EFR, EFD, EFG, EFH are not and we can abandon our search quickly. A few more possibilities reveal that no word with 3 letters or more in the above grid starts in the upper left-hand corner. Because a dictionary is sorted alphabetically, by prefix, we may be able to use a sorted array effectively in order for the computer to play Boggle and quickly determine all possible words on a grid. But we may still look for potentially more efficient data structures which take into account that we are searching for words that are constructed by incrementally extending the prefix. 3 Multi-Way Tries One possibility is to use a multi-way trie, where each node has a potential child for each letter in the alphabet. Consider the word SEE. We start at the root and follow the link labeled S, which gets us to a node on the second level in the tree. This tree indexes all words with first character S. From here we follow the link labeled E, which gets us to a node indexing all words that start with SE. After one more step we are at SEE. At this point we cannot be sure if this is a complete word or just a prefix for words stored in it. In order to record this, we can either store a Boolean (true if the current prefix is a complete word) or terminate the word with a special character that cannot appear in the word itself.

3 Tries L22.3 Below is an example of a multi-way trie indexing the three words BE, BEE, and BACCALAUREATE. false A B C D E Z false A B C D E Z false A B C D E Z true A B C D E Z true A B C D E Z While the paths to finding each word are quite short, including one more node than characters in the word, the data structure consumes a lot of space, because there are a lot of nearly empty arrays. An interesting property is that the lookup time for a word is O(k), where k is the number of characters in the word. This is independent of how many words are stored in the data structure! Contrast this with, say, balanced binary search trees where the search time is O(log(n)), where n is the number of words stored. For the latter analysis we assumed that key comparisons were constant time, which is not really true because the keys (which are strings) have to be compared character by character. So each comparison, while searching through a binary search tree, might take up to O(k) individual character comparisons, which would make it O(k log(n)) in the worst case. Compare that with O(k) for a trie. On the other hand, the wasted space of the multi-way trie with an array at each node costs time in practice. This is not only because this memory must be allocated, but because on modern architectures the so-called memory hierarchy means that accesses to memory cells close to each other will be much faster than accessing distant cells. You will learn more about this in Computer Systems.

4 Tries L Binary Tries The idea of the multi-way trie is quite robust, and there are useful special cases. One of these if we want to represent sets of numbers. In that case we can decompose the binary representation of numbers bit by bit in order to index data stored in the trie. We could start with the most significant or least significant bit, depending on the kind of numbers we expect. In this case every node would have at most two successors, one for 0 and one for 1. This does not waste nearly as much space and can be efficient for many purposes. 5 Linked Lists For the particular application we have in mind, namely searching for words on a grid of letters, we could either use multiway tries directly (wasting space) or use binary tries (wasting time and space, because each character is decomposed into individual bits). A compromise solution is replacing the array (which may end up mostly empty) with a linked list. This gives us two fundamentally different uses of pointers. Child pointers (drawn in blue) correspond to forward movement through the string. The next pointers of the linked list (drawn in red), on the other hand, connect what used to be parts of the same array list. In this representation, it also becomes natural to have the Boolean end of word flag stored with the final character, rather than one step below the final character like we did above. (This means it s no longer possible to store the empty string, however.) The tree above, containing BACCALAU- REATE, BE, and BEE, now looks like this: false b false a true e false c true e

5 Tries L22.5 If we add OR and BED, the result looks like this: false b false o false a true e true r false c true e true d For lookup, we have to make at most 26 comparisons between each character in the input string and the characters stored in the tree. Therefore search time is O(26 k) = O(k), where k is the length of the string. Insertion has the same asymptotic complexity bound. Note that this still does not change with the number of strings, only with its length. 6 Ternary Search Tries It should be apparent that we could get some performance gains over this linked list solution if we kept the linked lists sorted. This is an idea that allows us to motivate a more suitable data structure, a ternary search trie (TST) which combines ideas from binary search trees with tries. Roughly, at each node in a trie we store a binary search tree with characters as keys. The entries are pointers to the subtries. More precisely, at each node we store a character c and three pointers. The left subtree stores all words starting with characters alphabetically less than c. The right subtree stores all words starting with characters alphabetically greater than c and the middle stores a subtrie with all words starting with c, from the second character on. The middle children work exactly like the child pointers from our linked list implementation. The left and right pointers work like the next pointers from the linked list version, and are correspondingly drawn in red in the diagram below, which contains the words BE, BED, BEE, BACCALAUREATE, and OR. In this diagram, we represent the flag for end of word using the presence or absence of an X.

6 Tries L22.6 b First Character e o r Second Character a e Third Character c d We have not discussed any strategy for balancing TSTs. However, in the worst case (a completely unbalanced tree) we end up with something similar to the linked list implementation and we have to make at most 26 comparisons between each character in the input string and the characters stored in the tree. Therefore search time is O(26 k) = O(k), where k is the length of the string. Even when the embedded trees are perfectly balanced, the constant factor decreases, but not the asymptotic complexity because O(log(26) k) = O(k). 7 Specifying an Interface Specifying an interface for tries is tricky. If we want to just use tries as dictionaries, then we can store arbitrary elements, but we commit to strings as keys. In that sense our interface is not very abstract, but well-suited to our application. (To relate this to our discussion above, an X in the diagram above can represent the presence or absence of an element rather than a bool flag.)

7 Tries L22.7 typedef struct trie_header *trie; trie trie_new(); elem trie_lookup(trie TR, char *s); void trie_insert(trie TR, char *s, elem e); void trie_free(trie TR); The interface above is unable to handle freeing the data encoded in a trie. We discussed a client interface function elem_free when we ported binary search trees to C, but here we treat it as the client s responsibility to track and free their elements. If we typedef the type elem to be a void pointer, we now have a data structure without generic keys (keys are defined to be strings) but with generic values. By casting into and out of void*, we can store different values in the trie without duplicating the algorithm and data structure code the way we did in Claclab. 8 Adapting the interface However, it turns out we oversimplified. While the interface works well to use the trie as a kind of dictionary, it does not work well for our boggle application since we cannot tell if a string is a valid prefix of a complete word or not. If we want to be able to search for valid prefixes in tries, not just complete words, one option is to expose to the user a little bit of what the internal structure of a trie looks like. The function trie_lookup_prefix returns a sub-trie (or NULL if the prefix is not in the trie) and the function tnode_elem checks to see if there is data (a checkmark) stored in that location in the trie. typedef struct trie_node tnode; tnode *trie_lookup_prefix(trie T, char *s); elem tnode_elem(tnode *T); /* T!= NULL */ Exposing more of our interface always comes with a cost, because we may be less able to change our internal representation of tries once we have exposed a richer interface. However, if our goal is to use tries to play Boggle, some interface that checks prefixes is absolutely necessary.

8 Tries L Checking Invariants The declaration of the types is completely straightforward. typedef struct tst_node tst; struct tst_node { char c; /* discriminating character */ elem data; /* possible data element (void pointer) */ tst *left; /* left child in bst */ tst *middle; /* subtrie following c */ tst *right; /* right child in bst */ ; struct trie_header { tst *root; ; To check that a trie is valid we use two mutually recursive functions. One checks the order invariant for the binary search trees embedded in the trie, the other checks the correctness of the subtries. For mutually recursive functions we need to forward-declare the function which comes textually second in the file so that type checking by the compiler can be done in order. bool is_tst(tst *T, int lower, int upper); bool is_tst_root(tst *T); bool is_tst(tst *T, int lower, int upper) { if (T == NULL) return true; if (!(lower < T->c && T->c < upper)) return false; if (!(is_tst(t->left, lower, T->c))) return false; if (!(is_tst_root(t->middle))) return false; if (!(is_tst(t->right, T->c, upper))) return false; if (T->middle == NULL && T->data == NULL) return false; return true; bool is_tst_root(tst *T) { return is_tst(t, 0, ((int)char_max)+1);

9 Tries L22.9 It only makes sense to add one to CHAR_MAX because int is a bigger type than char. 0 and CHAR_MAX+1 essentially function as and + for checking the intervals of a binary search tree with strictly positive character values as keys. 10 Implementing Lookup on TSTs Implementing lookup is just a direct combination of traversing a trie and searching through binary search trees. We pass a trie T, a string s and an index i which should be a valid string index so that we can compare s[i] to the node s character. If T is null, the word is not stored in the trie and we return NULL. On the other hand, if we are at the end of the string (s[i+1] = \0 ) we return the stored data. Otherwise, we continue lookup in the left, middle, or right subtree as appropriate. Important for the last case: if the string character s[i] is equal to the character stored at the node, then we look for the remainder of the word in the middle subtrie. This is implemented by passing i + 1 to the subtrie. tnode *tnode_lookup(tnode *T, char *s, size_t i) { REQUIRES(is_tst_root(T)); REQUIRES(s!= NULL); REQUIRES(i < strlen(s)); if (T == NULL) return NULL; if (s[i] < T->c) return tnode_lookup(t->left, s, i); if (s[i] > T->c) return tnode_lookup(t->right, s, i); ASSERT(s[i] == T->c); if (s[i+1] == \0 ) return T; return tnode_lookup(t->middle, s, i+1); This function can then be used to implement several interface functions: tnode *trie_lookup_prefix(trie *TR, char *s) { REQUIRES(is_trie(TR)); REQUIRES(s!= NULL); return tnode_lookup(tr->root, s, 0);

10 Tries L22.10 elem tnode_elem(tnode *T) { REQUIRES(is_tst_root(T)); REQUIRES(T!= NULL); return T->data; /* could be NULL */ elem trie_lookup(trie TR, char *s) { REQUIRES(is_trie(TR)); REQUIRES(s!= NULL); tnode *T = trie_lookup_prefix(tr, s); if (T == NULL) return NULL; else return tnode_elem(t); 11 Implementing Insertion Insertion follows the same structure as search, which is typical for the kind of data structure we have been considering in the last few weeks. If the tree to insert into is null, we create a new node with the character of the string we are currently considering (the ith) and null children and then continue with the insertion algorithm. tnode *tnode_insert(tnode *T, char *s, size_t i, elem e) { REQUIRES(is_tst_root(T)); REQUIRES(s!= NULL); REQUIRES(i < strlen(s)); if (T == NULL) { T = xmalloc(sizeof(struct trie_node)); T->c = s[i]; T->data = NULL; T->left = NULL; T->right = NULL;

11 Tries L22.11 T->middle = NULL; ASSERT(T!= NULL); if (s[i] < T->c) T->left = tnode_insert(t->left, s, i, e); else if (s[i] > T->c) T->right = tnode_insert(t->right, s, i, e); else if (s[i+1] == \0 ) T->data = e; else T->middle = tnode_insert(t->middle, s, i+1, e); return T; As usual with recursive algorithms, we return the the trie after insertion to handle the null case gracefully, but we operate imperatively on the subtries. At the top level we just insert into the root, with an initial index of 0. At this (non-recursive) level, insertion is done purely by modifying the data structure. void trie_insert(trie TR, char *s, elem e) { REQUIRES(is_trie(TR)); REQUIRES(s!= NULL); TR->root = tnode_insert(tr->root, s, 0, e);

12 Tries L22.12 Exercises Exercise 1 Implement the game of Boggle as sketched in this lecture. Make sure to pick the letters according to the distribution of their occurrence in the English language. You might use the Scrabble dictionary itself, for example, to calculate the relative frequency of the letters. If you are ambitious, try to design a simple textual interface to print a random grid and then input words from the human player and show the words missed by the player. Exercise 2 Modify the implementation of search in TSTs so it can process a star ( * ) character in the search string. It can match any number of characters for words stored in the trie. This matching is done by adding all matching string to a queue that is an input argument to the generalized search function. For example, after we insert BE, BED, and BACCALAUREATE, the string "BE*" matches the first two words, and "*A*" matches the only the third, in three different ways. The search string "*" should match the entire set of words stored in the trie and produce them in alphabetical order. You should decide if the different ways to match a search string should show up multiple times in the result queue or just one. Exercise 3 Modify TSTs to use a special non-alphabetic character (either period. or the nil character \0 ), which is shown as a small filled circle in the diagram, to represent the end of the word. B A C E C D

13 Tries L22.13 Exercise 4 Using this modified TST implementation from the question above, allow repeated searching of prefixes with the following interface: /* Prefix search interface */ typedef struct trie_node tnode; tnode *trie_root(trie TR); tnode *tnode_lookup_prefix(tnode *T, char *s); /* i < strlen(s) */ elem tnode_elem(tnode *T); The tnode pointer returned by trie_root or tnode_lookup_prefix should be a pointer to the root of a TST, and tnode_elem will look for the the special character. or \0 by following left and right pointers and return any data stored at that special node. Exercise 5 Consider other implementations of the interface above that allow repeated searching of prefixes.

Lecture Notes on Tries

Lecture Notes on Tries Lecture Notes on Tries 15-122: Principles of Imperative Computation Thomas Cortina, Frank Pfenning, Rob Simmons, Penny Anderson Lecture 21 November 10, 2014 1 Introduction In the data structures implementing

More information

Lecture Notes on Tries

Lecture Notes on Tries Lecture Notes on Tries 15-122: Principles of Imperative Computation Thomas Cortina Notes by Frank Pfenning Lecture 24 April 19, 2011 1 Introduction In the data structures implementing associative arrays

More information

Lecture Notes on Binary Search Trees

Lecture Notes on Binary Search Trees Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning Lecture 17 1 Introduction In the previous two lectures we have seen how to exploit the structure of binary

More information

Lecture Notes on Binary Search Trees

Lecture Notes on Binary Search Trees Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 15 March 6, 2014 1 Introduction In this lecture, we will continue considering associative

More information

Lecture 15 Binary Search Trees

Lecture 15 Binary Search Trees Lecture 15 Binary Search Trees 15-122: Principles of Imperative Computation (Fall 2017) Frank Pfenning, André Platzer, Rob Simmons, Iliano Cervesato In this lecture, we will continue considering ways to

More information

Lecture Notes on Binary Search Trees

Lecture Notes on Binary Search Trees Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Tom Cortina Lecture 15 October 14, 2010 1 Introduction In the previous two lectures we have seen how to exploit the structure

More information

Lecture 15 Notes Binary Search Trees

Lecture 15 Notes Binary Search Trees Lecture 15 Notes Binary Search Trees 15-122: Principles of Imperative Computation (Spring 2016) Frank Pfenning, André Platzer, Rob Simmons 1 Introduction In this lecture, we will continue considering ways

More information

Lecture Notes on Binary Search Trees

Lecture Notes on Binary Search Trees Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 16 March 17, 2015 1 Introduction In this lecture, we will continue considering ways

More information

Exam Principles of Imperative Computation, Summer 2011 William Lovas. June 24, 2011

Exam Principles of Imperative Computation, Summer 2011 William Lovas. June 24, 2011 Exam 3 15-122 Principles of Imperative Computation, Summer 2011 William Lovas June 24, 2011 Name: Sample Solution Andrew ID: wlovas Instructions This exam is closed-book with one double-sided sheet of

More information

Midterm II Exam Principles of Imperative Computation Frank Pfenning. March 31, 2011

Midterm II Exam Principles of Imperative Computation Frank Pfenning. March 31, 2011 Midterm II Exam 15-122 Principles of Imperative Computation Frank Pfenning March 31, 2011 Name: Sample Solution Andrew ID: fp Section: Instructions This exam is closed-book with one sheet of notes permitted.

More information

Lecture Notes on Priority Queues

Lecture Notes on Priority Queues Lecture Notes on Priority Queues 15-122: Principles of Imperative Computation Frank Pfenning Lecture 16 October 18, 2012 1 Introduction In this lecture we will look at priority queues as an abstract type

More information

Lecture 17 Notes Priority Queues

Lecture 17 Notes Priority Queues Lecture 17 Notes Priority Queues 15-122: Principles of Imperative Computation (Summer 1 2015) Frank Pfenning, Rob Simmons 1 Introduction In this lecture we will look at priority queues as an abstract type

More information

Final Exam Principles of Imperative Computation Frank Pfenning, Tom Cortina, William Lovas. December 10, Name: Andrew ID: Section:

Final Exam Principles of Imperative Computation Frank Pfenning, Tom Cortina, William Lovas. December 10, Name: Andrew ID: Section: Final Exam 15-122 Principles of Imperative Computation Frank Pfenning, Tom Cortina, William Lovas December 10, 2010 Name: Andrew ID: Section: Instructions This exam is closed-book with one sheet of notes

More information

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

Trees. Chapter 6. strings. 3 Both position and Enumerator are similar in concept to C++ iterators, although the details are quite different. Chapter 6 Trees In a hash table, the items are not stored in any particular order in the table. This is fine for implementing Sets and Maps, since for those abstract data types, the only thing that matters

More information

Lecture 16 Notes AVL Trees

Lecture 16 Notes AVL Trees Lecture 16 Notes AVL Trees 15-122: Principles of Imperative Computation (Spring 2016) Frank Pfenning 1 Introduction Binary search trees are an excellent data structure to implement associative arrays,

More information

Lecture Notes on Interfaces

Lecture Notes on Interfaces Lecture Notes on Interfaces 15-122: Principles of Imperative Computation Frank Pfenning Lecture 14 October 16, 2012 1 Introduction The notion of an interface to an implementation of an abstract data type

More information

Lecture 17 Priority Queues

Lecture 17 Priority Queues Lecture 17 Priority Queues 15-122: Principles of Imperative Computation (Spring 2018) Frank Pfenning, Rob Simmons In this lecture we will look at priority queues as an abstract type and discuss several

More information

Friday Four Square! 4:15PM, Outside Gates

Friday Four Square! 4:15PM, Outside Gates Binary Search Trees Friday Four Square! 4:15PM, Outside Gates Implementing Set On Monday and Wednesday, we saw how to implement the Map and Lexicon, respectively. Let's now turn our attention to the Set.

More information

Lecture 10 Notes Linked Lists

Lecture 10 Notes Linked Lists Lecture 10 Notes Linked Lists 15-122: Principles of Imperative Computation (Spring 2016) Frank Pfenning, Rob Simmons, André Platzer 1 Introduction In this lecture we discuss the use of linked lists to

More information

Lecture 16 AVL Trees

Lecture 16 AVL Trees Lecture 16 AVL Trees 15-122: Principles of Imperative Computation (Fall 2018) Frank Pfenning Binary search trees are an excellent data structure to implement associative arrays, maps, sets, and similar

More information

Lecture 13 Notes Sets

Lecture 13 Notes Sets Lecture 13 Notes Sets 15-122: Principles of Imperative Computation (Spring 2016) Frank Pfenning, Rob Simmons 1 Introduction In this lecture, we will discuss the data structure of hash tables further and

More information

Lecture 23 Representing Graphs

Lecture 23 Representing Graphs Lecture 23 Representing Graphs 15-122: Principles of Imperative Computation (Fall 2018) Frank Pfenning, André Platzer, Rob Simmons, Penny Anderson, Iliano Cervesato In this lecture we introduce graphs.

More information

Lecture 13 Hash Dictionaries

Lecture 13 Hash Dictionaries Lecture 13 Hash Dictionaries 15-122: Principles of Imperative Computation (Fall 2018) Frank Pfenning, Rob Simmons, Iliano Cervesato In this lecture, we will discuss the data structure of hash tables further

More information

Lecture 10 Notes Linked Lists

Lecture 10 Notes Linked Lists Lecture 10 Notes Linked Lists 15-122: Principles of Imperative Computation (Summer 1 2015) Frank Pfenning, Rob Simmons, André Platzer 1 Introduction In this lecture we discuss the use of linked lists to

More information

Binary Trees. BSTs. For example: Jargon: Data Structures & Algorithms. root node. level: internal node. edge.

Binary Trees. BSTs. For example: Jargon: Data Structures & Algorithms. root node. level: internal node. edge. Binary Trees 1 A binary tree is either empty, or it consists of a node called the root together with two binary trees called the left subtree and the right subtree of the root, which are disjoint from

More information

Lecture 13 Notes Sets

Lecture 13 Notes Sets Lecture 13 Notes Sets 15-122: Principles of Imperative Computation (Fall 2015) Frank Pfenning, Rob Simmons 1 Introduction In this lecture, we will discuss the data structure of hash tables further and

More information

Exam Principles of Imperative Computation, Summer 2011 William Lovas. June 24, 2011

Exam Principles of Imperative Computation, Summer 2011 William Lovas. June 24, 2011 Exam 3 15-122 Principles of Imperative Computation, Summer 2011 William Lovas June 24, 2011 Name: Andrew ID: Instructions This exam is closed-book with one double-sided sheet of notes permitted. You have

More information

CS106X Handout 39 Autumn 2012 November 28 th, 2012 CS106X Midterm Examination II

CS106X Handout 39 Autumn 2012 November 28 th, 2012 CS106X Midterm Examination II CS106X Handout 39 Autumn 2012 November 28 th, 2012 CS106X Midterm Examination II This is closed book, closed notes, closed reader, closed everything exam. If you re taking the exam remotely, you can telephone

More information

Lecture 11 Unbounded Arrays

Lecture 11 Unbounded Arrays Lecture 11 Unbounded Arrays 15-122: Principles of Imperative Computation (Spring 2018) Rob Simmons, Frank Pfenning Arrays have efficient O(1) access to elements given an index, but their size is set at

More information

Lecture Notes on Generic Data Structures

Lecture Notes on Generic Data Structures Lecture Notes on Generic Data Structures 15-122: Principles of Imperative Computation Frank Pfenning, Penny Anderson Lecture 21 November 7, 2013 1 Introduction Using void* to represent pointers to values

More information

Need Backtracking! L 0 A 1 B 2 K 3 P 4 C 5 I 6 Z 7 S 8 A 9 N 10 X 11 A 12 N 13 X 14 P 15

Need Backtracking! L 0 A 1 B 2 K 3 P 4 C 5 I 6 Z 7 S 8 A 9 N 10 X 11 A 12 N 13 X 14 P 15 CSE 100: TRIES Need Backtracking! L 0 A 1 B 2 K 3 P 4 C 5 I 6 Z 7 S 8 A 9 N 10 X 11 A 12 N 13 X 14 P 15 isonboard(g,v, word ) ( v is the vertex where the search starts, word is the word we are looking

More information

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer)

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer) COSC 2007 Data Structures II Final Exam Thursday, April 13 th, 2006 This is a closed book and closed notes exam. There are total 3 parts. Please answer the questions in the provided space and use back

More information

Lecture Notes on Binary Decision Diagrams

Lecture Notes on Binary Decision Diagrams Lecture Notes on Binary Decision Diagrams 15-122: Principles of Imperative Computation William Lovas Notes by Frank Pfenning Lecture 25 April 21, 2011 1 Introduction In this lecture we revisit the important

More information

Lecture 18 Restoring Invariants

Lecture 18 Restoring Invariants Lecture 18 Restoring Invariants 15-122: Principles of Imperative Computation (Spring 2018) Frank Pfenning In this lecture we will implement heaps and operations on them. The theme of this lecture is reasoning

More information

Lecture 24 Notes Search in Graphs

Lecture 24 Notes Search in Graphs Lecture 24 Notes Search in Graphs 15-122: Principles of Imperative Computation (Spring 2016) Frank Pfenning, André Platzer, Rob Simmons, Penny Anderson 1 Introduction In this lecture, we will discuss the

More information

- 1 - Handout #22S May 24, 2013 Practice Second Midterm Exam Solutions. CS106B Spring 2013

- 1 - Handout #22S May 24, 2013 Practice Second Midterm Exam Solutions. CS106B Spring 2013 CS106B Spring 2013 Handout #22S May 24, 2013 Practice Second Midterm Exam Solutions Based on handouts by Eric Roberts and Jerry Cain Problem One: Reversing a Queue One way to reverse the queue is to keep

More information

CMSC 341 Lecture 10 Binary Search Trees

CMSC 341 Lecture 10 Binary Search Trees CMSC 341 Lecture 10 Binary Search Trees John Park Based on slides from previous iterations of this course Review: Tree Traversals 2 Traversal Preorder, Inorder, Postorder H X M A K B E N Y L G W UMBC CMSC

More information

Trees, Part 1: Unbalanced Trees

Trees, Part 1: Unbalanced Trees Trees, Part 1: Unbalanced Trees The first part of this chapter takes a look at trees in general and unbalanced binary trees. The second part looks at various schemes to balance trees and/or make them more

More information

: Principles of Imperative Computation. Summer Assignment 4. Due: Monday, June 11, 2012 in class

: Principles of Imperative Computation. Summer Assignment 4. Due: Monday, June 11, 2012 in class 15-122 Assignment 4 Page 1 of 8 15-122 : Principles of Imperative Computation Summer 1 2012 Assignment 4 (Theory Part) Due: Monday, June 11, 2012 in class Name: Andrew ID: Recitation: The written portion

More information

CS-301 Data Structure. Tariq Hanif

CS-301 Data Structure. Tariq Hanif 1. The tree data structure is a Linear data structure Non-linear data structure Graphical data structure Data structure like queue FINALTERM EXAMINATION Spring 2012 CS301- Data Structure 25-07-2012 2.

More information

Binary Search Trees, etc.

Binary Search Trees, etc. Chapter 12 Binary Search Trees, etc. Binary Search trees are data structures that support a variety of dynamic set operations, e.g., Search, Minimum, Maximum, Predecessors, Successors, Insert, and Delete.

More information

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 The data of the problem is of 2GB and the hard disk is of 1GB capacity, to solve this problem we should Use better data structures

More information

Binary Search Trees Treesort

Binary Search Trees Treesort Treesort CS 311 Data Structures and Algorithms Lecture Slides Friday, November 13, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org 2005 2009

More information

CSE100. Advanced Data Structures. Lecture 12. (Based on Paul Kube course materials)

CSE100. Advanced Data Structures. Lecture 12. (Based on Paul Kube course materials) CSE100 Advanced Data Structures Lecture 12 (Based on Paul Kube course materials) CSE 100 Coding and decoding with a Huffman coding tree Huffman coding tree implementation issues Priority queues and priority

More information

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

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge Trees & Heaps Week 12 Gaddis: 20 Weiss: 21.1-3 CS 5301 Fall 2018 Jill Seaman!1 Tree: non-recursive definition! Tree: set of nodes and directed edges - root: one node is distinguished as the root - Every

More information

Binary Search Trees. Contents. Steven J. Zeil. July 11, Definition: Binary Search Trees The Binary Search Tree ADT...

Binary Search Trees. Contents. Steven J. Zeil. July 11, Definition: Binary Search Trees The Binary Search Tree ADT... Steven J. Zeil July 11, 2013 Contents 1 Definition: Binary Search Trees 2 1.1 The Binary Search Tree ADT.................................................... 3 2 Implementing Binary Search Trees 7 2.1 Searching

More information

CS102 Binary Search Trees

CS102 Binary Search Trees CS102 Binary Search Trees Prof Tejada 1 To speed up insertion, removal and search, modify the idea of a Binary Tree to create a Binary Search Tree (BST) Binary Search Trees Binary Search Trees have one

More information

CSCI Trees. Mark Redekopp David Kempe

CSCI Trees. Mark Redekopp David Kempe CSCI 104 2-3 Trees Mark Redekopp David Kempe Trees & Maps/Sets C++ STL "maps" and "sets" use binary search trees internally to store their keys (and values) that can grow or contract as needed This allows

More information

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

A set of nodes (or vertices) with a single starting point Binary Search Trees Understand tree terminology Understand and implement tree traversals Define the binary search tree property Implement binary search trees Implement the TreeSort algorithm 2 A set of

More information

Binary Trees and Binary Search Trees

Binary Trees and Binary Search Trees Binary Trees and Binary Search Trees Learning Goals After this unit, you should be able to... Determine if a given tree is an instance of a particular type (e.g. binary, and later heap, etc.) Describe

More information

We have the pointers reference the next node in an inorder traversal; called threads

We have the pointers reference the next node in an inorder traversal; called threads Leaning Objective: In this Module you will be learning the following: Threaded Binary Tree Introduction: Threaded Binary Tree is also a binary tree in which all left child pointers that are NULL (in Linked

More information

You must include this cover sheet. Either type up the assignment using theory5.tex, or print out this PDF.

You must include this cover sheet. Either type up the assignment using theory5.tex, or print out this PDF. 15-122 Assignment 5 Page 1 of 11 15-122 : Principles of Imperative Computation Fall 2012 Assignment 5 (Theory Part) Due: Tuesday, October 30, 2012 at the beginning of lecture Name: Andrew ID: Recitation:

More information

15 122: Principles of Imperative Computation. Practice Exam August 4, 2015

15 122: Principles of Imperative Computation. Practice Exam August 4, 2015 15 122: Principles of Imperative Computation Practice Exam August 4, 2015 15-122 Practice Exam Page 2 of 17 1. Fun with C. The following C programs have between 0 and 1 errors in them. If the function

More information

Lecture Notes on Generic Data Structures

Lecture Notes on Generic Data Structures Lecture Notes on Generic Data Structures 15-122: Principles of Imperative Computation Frank Pfenning Lecture 22 November 15, 2012 1 Introduction Using void* to represent pointers to values of arbitrary

More information

Lecture 24 Search in Graphs

Lecture 24 Search in Graphs Lecture 24 Search in Graphs 15-122: Principles of Imperative Computation (Fall 2018) Frank Pfenning, André Platzer, Rob Simmons, Penny Anderson, Iliano Cervesato In this lecture, we will discuss the question

More information

Lecture 12 Notes Hash Tables

Lecture 12 Notes Hash Tables Lecture 12 Notes Hash Tables 15-122: Principles of Imperative Computation (Spring 2016) Frank Pfenning, Rob Simmons 1 Introduction In this lecture we re-introduce the dictionaries that were implemented

More information

Recitation 9. Prelim Review

Recitation 9. Prelim Review Recitation 9 Prelim Review 1 Heaps 2 Review: Binary heap min heap 1 2 99 4 3 PriorityQueue Maintains max or min of collection (no duplicates) Follows heap order invariant at every level Always balanced!

More information

CS 104 (Spring 2014) Final Exam 05/09/2014

CS 104 (Spring 2014) Final Exam 05/09/2014 CS 104 (Spring 2014) Final Exam 05/09/2014 G o o d L u c k Your Name, USC username, and Student ID: This exam has 8 pages and 8 questions. If yours does not, please contact us immediately. Please read

More information

Final exam. CS 2110, December 15, 2016, 9:00AM

Final exam. CS 2110, December 15, 2016, 9:00AM Final exam CS 2110, December 15, 2016, 9:00AM Question Short Trie Loop Exp Rec Gen Span Mon BigO Data Total Max 20 7 9 10 9 9 8 10 10 8 100 Score Grader The exam is closed book and closed notes. Do not

More information

Trees can be used to store entire records from a database, serving as an in-memory representation of the collection of records in a file.

Trees can be used to store entire records from a database, serving as an in-memory representation of the collection of records in a file. Large Trees 1 Trees can be used to store entire records from a database, serving as an in-memory representation of the collection of records in a file. Trees can also be used to store indices of the collection

More information

CS 241 Data Organization Binary Trees

CS 241 Data Organization Binary Trees CS 241 Data Organization Binary Trees Brooke Chenoweth University of New Mexico Fall 2017 Binary Tree: Kernighan and Ritchie 6.5 Read a file and count the occurrences of each word. now is the time for

More information

BINARY SEARCH TREES cs2420 Introduction to Algorithms and Data Structures Spring 2015

BINARY SEARCH TREES cs2420 Introduction to Algorithms and Data Structures Spring 2015 BINARY SEARCH TREES cs2420 Introduction to Algorithms and Data Structures Spring 2015 1 administrivia 2 -assignment 7 due tonight at midnight -asking for regrades through assignment 5 and midterm must

More information

CS106X Handout 35 Winter 2018 March 12 th, 2018 CS106X Midterm Examination

CS106X Handout 35 Winter 2018 March 12 th, 2018 CS106X Midterm Examination CS106X Handout 35 Winter 2018 March 12 th, 2018 CS106X Midterm Examination This is an open-book, open-note, closed-electronic-device exam. You needn t write #includes, and you may (and you re even encouraged

More information

CSC148 Week 7. Larry Zhang

CSC148 Week 7. Larry Zhang CSC148 Week 7 Larry Zhang 1 Announcements Test 1 can be picked up in DH-3008 A1 due this Saturday Next week is reading week no lecture, no labs no office hours 2 Recap Last week, learned about binary trees

More information

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination University of Illinois at Urbana-Champaign Department of Computer Science Second Examination CS 225 Data Structures and Software Principles Spring 2014 7-10p, Tuesday, April 8 Name: NetID: Lab Section

More information

Multi-way Search Trees! M-Way Search! M-Way Search Trees Representation!

Multi-way Search Trees! M-Way Search! M-Way Search Trees Representation! Lecture 10: Multi-way Search Trees: intro to B-trees 2-3 trees 2-3-4 trees Multi-way Search Trees A node on an M-way search tree with M 1 distinct and ordered keys: k 1 < k 2 < k 3

More information

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

BST Implementation. Data Structures. Lecture 4 Binary search trees (BST) Dr. Mahmoud Attia Sakr University of Ain Shams Lecture 4 Binary search trees (BST) Dr. Mahmoud Attia Sakr mahmoud.sakr@cis.asu.edu.eg Cairo, Egypt, October 2012 Binary Search Trees (BST) 1. Hierarchical data structure with a single reference to root

More information

Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees

Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees Linked representation of binary tree Again, as with linked list, entire tree can be represented with a single pointer -- in this

More information

Implementing Dynamic Minimal-prefix Tries

Implementing Dynamic Minimal-prefix Tries SOFTWARE PRACTICE AND EXPERIENCE, VOL. 21(10), 1027 1040 (OCTOBER 1991) Implementing Dynamic Minimal-prefix Tries JOHN A. DUNDAS III Jet Propulsion Laboratory, California Institute of Technology, Mail

More information

CSE100 Practice Final Exam Section C Fall 2015: Dec 10 th, Problem Topic Points Possible Points Earned Grader

CSE100 Practice Final Exam Section C Fall 2015: Dec 10 th, Problem Topic Points Possible Points Earned Grader CSE100 Practice Final Exam Section C Fall 2015: Dec 10 th, 2015 Problem Topic Points Possible Points Earned Grader 1 The Basics 40 2 Application and Comparison 20 3 Run Time Analysis 20 4 C++ and Programming

More information

Chapter 20: Binary Trees

Chapter 20: Binary Trees Chapter 20: Binary Trees 20.1 Definition and Application of Binary Trees Definition and Application of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two other

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques () Lecture 6 January 24, 2018 Binary Search Trees (Lecture notes Chapter 7) Announcements Homework 2: Computing Human Evolution due Tuesday, September 19 th Reading:

More information

SCJ2013 Data Structure & Algorithms. Binary Search Tree. Nor Bahiah Hj Ahmad

SCJ2013 Data Structure & Algorithms. Binary Search Tree. Nor Bahiah Hj Ahmad SCJ2013 Data Structure & Algorithms Binary Search Tree Nor Bahiah Hj Ahmad Binary Search Tree A binary search tree has the following properties: For every node n in the tree Value of n is greater than

More information

Module 4: Index Structures Lecture 13: Index structure. The Lecture Contains: Index structure. Binary search tree (BST) B-tree. B+-tree.

Module 4: Index Structures Lecture 13: Index structure. The Lecture Contains: Index structure. Binary search tree (BST) B-tree. B+-tree. The Lecture Contains: Index structure Binary search tree (BST) B-tree B+-tree Order file:///c /Documents%20and%20Settings/iitkrana1/My%20Documents/Google%20Talk%20Received%20Files/ist_data/lecture13/13_1.htm[6/14/2012

More information

Lecture Notes on Hash Tables

Lecture Notes on Hash Tables Lecture Notes on Hash Tables 15-122: Principles of Imperative Computation Frank Pfenning Lecture 13 February 24, 2011 1 Introduction In this lecture we introduce so-called associative arrays, that is,

More information

Treaps. 1 Binary Search Trees (BSTs) CSE341T/CSE549T 11/05/2014. Lecture 19

Treaps. 1 Binary Search Trees (BSTs) CSE341T/CSE549T 11/05/2014. Lecture 19 CSE34T/CSE549T /05/04 Lecture 9 Treaps Binary Search Trees (BSTs) Search trees are tree-based data structures that can be used to store and search for items that satisfy a total order. There are many types

More information

Lecture Notes on Memory Layout

Lecture Notes on Memory Layout Lecture Notes on Memory Layout 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 11 1 Introduction In order to understand how programs work, we can consider the functions,

More information

Trees. Eric McCreath

Trees. Eric McCreath Trees Eric McCreath 2 Overview In this lecture we will explore: general trees, binary trees, binary search trees, and AVL and B-Trees. 3 Trees Trees are recursive data structures. They are useful for:

More information

Lecture 12 Hash Tables

Lecture 12 Hash Tables Lecture 12 Hash Tables 15-122: Principles of Imperative Computation (Spring 2018) Frank Pfenning, Rob Simmons Dictionaries, also called associative arrays as well as maps, are data structures that are

More information

Lecture Notes on Dynamic Programming

Lecture Notes on Dynamic Programming Lecture Notes on Dynamic Programming 15-122: Principles of Imperative Computation Frank Pfenning Lecture 23 November 16, 2010 1 Introduction In this lecture we introduce dynamic programming, which is a

More information

Fall, 2015 Prof. Jungkeun Park

Fall, 2015 Prof. Jungkeun Park Data Structures and Algorithms Binary Search Trees Fall, 2015 Prof. Jungkeun Park Copyright Notice: This material is modified version of the lecture slides by Prof. Rada Mihalcea in Univ. of North Texas.

More information

IX. Binary Trees (Chapter 10)

IX. Binary Trees (Chapter 10) IX. Binary Trees (Chapter 10) -1- A. Introduction: Searching a linked list. 1. Linear Search /* To linear search a list for a particular Item */ 1. Set Loc = 0; 2. Repeat the following: a. If Loc >= length

More information

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the elements may locate at far positions

More information

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

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge Trees (& Heaps) Week 12 Gaddis: 20 Weiss: 21.1-3 CS 5301 Spring 2015 Jill Seaman 1 Tree: non-recursive definition! Tree: set of nodes and directed edges - root: one node is distinguished as the root -

More information

Computer Science Foundation Exam

Computer Science Foundation Exam Computer Science Foundation Exam August 26, 2017 Section I A DATA STRUCTURES NO books, notes, or calculators may be used, and you must work entirely on your own. Name: UCFID: NID: Question # Max Pts Category

More information

COMP4128 Programming Challenges

COMP4128 Programming Challenges Multi- COMP4128 Programming Challenges School of Computer Science and Engineering UNSW Australia Table of Contents 2 Multi- 1 2 Multi- 3 3 Multi- Given two strings, a text T and a pattern P, find the first

More information

Week 2. TA Lab Consulting - See schedule (cs400 home pages) Peer Mentoring available - Friday 8am-12pm, 12:15-1:30pm in 1289CS

Week 2. TA Lab Consulting - See schedule (cs400 home pages) Peer Mentoring available - Friday 8am-12pm, 12:15-1:30pm in 1289CS ASSIGNMENTS h0 available and due before 10pm on Monday 1/28 h1 available and due before 10pm on Monday 2/4 p1 available and due before 10pm on Thursday 2/7 Week 2 TA Lab Consulting - See schedule (cs400

More information

Crit-bit Trees. Adam Langley (Version )

Crit-bit Trees. Adam Langley (Version ) Crit-bit Trees Adam Langley (agl@imperialviolet.org) (Version 20080926) 1. Introduction This code is taken from Dan Bernstein s qhasm and implements a binary crit-bit (alsa known as PATRICA) tree for NUL

More information

Lecture Notes on Queues

Lecture Notes on Queues Lecture Notes on Queues 15-122: Principles of Imperative Computation Frank Pfenning Lecture 9 September 25, 2012 1 Introduction In this lecture we introduce queues as a data structure and linked lists

More information

Crit-bit Trees. Adam Langley (Version )

Crit-bit Trees. Adam Langley (Version ) CRITBIT CWEB OUTPUT 1 Crit-bit Trees Adam Langley (agl@imperialviolet.org) (Version 20080926) 1. Introduction This code is taken from Dan Bernstein s qhasm and implements a binary crit-bit (alsa known

More information

Lecture 25 Spanning Trees

Lecture 25 Spanning Trees Lecture 25 Spanning Trees 15-122: Principles of Imperative Computation (Fall 2018) Frank Pfenning, Iliano Cervesato The following is a simple example of a connected, undirected graph with 5 vertices (A,

More information

Garbage Collection: recycling unused memory

Garbage Collection: recycling unused memory Outline backtracking garbage collection trees binary search trees tree traversal binary search tree algorithms: add, remove, traverse binary node class 1 Backtracking finding a path through a maze is an

More information

Trees. (Trees) Data Structures and Programming Spring / 28

Trees. (Trees) Data Structures and Programming Spring / 28 Trees (Trees) Data Structures and Programming Spring 2018 1 / 28 Trees A tree is a collection of nodes, which can be empty (recursive definition) If not empty, a tree consists of a distinguished node r

More information

CMSC 341 Lecture 16/17 Hashing, Parts 1 & 2

CMSC 341 Lecture 16/17 Hashing, Parts 1 & 2 CMSC 341 Lecture 16/17 Hashing, Parts 1 & 2 Prof. John Park Based on slides from previous iterations of this course Today s Topics Overview Uses and motivations of hash tables Major concerns with hash

More information

CP2 Revision. theme: dynamic datatypes & data structures

CP2 Revision. theme: dynamic datatypes & data structures CP2 Revision theme: dynamic datatypes & data structures structs can hold any combination of datatypes handled as single entity struct { }; ;

More information

CS 307 Final Spring 2009

CS 307 Final Spring 2009 Points off 1 2 3 4 5 Total off Net Score CS 307 Final Spring 2009 Name UTEID login name Instructions: 1. Please turn off your cell phones. 2. There are 5 questions on this test. 3. You have 3 hours to

More information

Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi.

Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi. Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi Lecture 18 Tries Today we are going to be talking about another data

More information

CSE100. Advanced Data Structures. Lecture 13. (Based on Paul Kube course materials)

CSE100. Advanced Data Structures. Lecture 13. (Based on Paul Kube course materials) CSE100 Advanced Data Structures Lecture 13 (Based on Paul Kube course materials) CSE 100 Priority Queues in Huffman s algorithm Heaps and Priority Queues Time and space costs of coding with Huffman codes

More information

CSCI2100B Data Structures Trees

CSCI2100B Data Structures Trees CSCI2100B Data Structures Trees Irwin King king@cse.cuhk.edu.hk http://www.cse.cuhk.edu.hk/~king Department of Computer Science & Engineering The Chinese University of Hong Kong Introduction General Tree

More information

Binary Trees (and Big O notation)

Binary Trees (and Big O notation) Binary Trees (and Big O notation) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute

More information