Lecture 13: AVL Trees and Binary Heaps

Size: px
Start display at page:

Download "Lecture 13: AVL Trees and Binary Heaps"

Transcription

1 Data Structures Brett Bernstein Lecture 13: AVL Trees and Binary Heaps Review Exercises 1. ( ) Interview question: Given an array show how to shue it randomly so that any possible reordering is equally likely. static void shue(int[] arr) 2. Write a function that given the root of a binary search tree returns the node with the largest value. public static BSTNode<Integer> getlargest(bstnode<integer> root) 3. Explain how you would use a binary search tree to implement the Map ADT. We have included it below to remind you. Map.java //Stores a mapping of keys to values public interface Map<K,V> { //Adds key to the map with the associated value. If key already //exists, the associated value is replaced. void put(k key, V value); //Gets the value for the given key, or null if it isn't found. V get(k key); //Returns true if the key is in the map, or false otherwise. boolean containskey(k key); //Removes the key from the map void remove(k key); //Number of keys in the map int size(); } What requirements must be placed on the Map? 4. Consider the following binary search tree

2 Perform the following operations in order. (a) Remove 1. (b) Remove 1. (c) Add 13. (d) Add 8.. Suppose we begin with an empty BST. What order of add operations will yield the tallest possible tree? Review Solutions 1. One method (popular in programs like Excel) is to generate a random double corresponding to each element of the array, and then sort the array by the corresponding doubles. Here is a dierent method that avoids sorting (used by Collections.shue). import java.util.random; RandomShue.java public class RandomShue { static void swap(int[] arr, int i, int j) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } //Iterative implementation public static void shue(int[] arr) { Random ran = new Random(); for (int i = arr.length 1; i >= 1; i) swap(arr,i,ran.nextint(i)); } //Recursive implementation public static void shuerec(int[] arr) { srhelp(arr, arr.length, new Random()); } public static void srhelp(int[] arr, int len, Random ran) { if (len <= 1) return; swap(arr, len 1, ran.nextint(len)); srhelp(arr,len 1,ran); } } 2

3 Above we give an iterative and a recursive implementation. We rst randomly choose one of the elements and swap it into the nal position. Then we repeat the process on the rst n 1 elements (i.e., randomly choose last element, and then randomly shue rst n 1 elements). 2. public static BSTNode<Integer> getlargest(bstnode<integer> root) { while (root.getright()!= null) root = root.getright(); return root; } 3. We require the keys of the Map to be Comparable or a Comparator to be provided. In each node instead of simply storing a value, store a key-value pair (i.e., an entry). The BST will be ordered by the keys. Here all operations above will be Θ(h) in the worst case (we don't have containsvalue above which would always be Θ(n)). In a moment, we will show how to achieve Θ(lg n) height trees which gives an ecient Map implementation without needing a hash function (but we need ordered keys). 4. (a) (b) (c) (d)

4 Ascending or descending order (i.e., sorted or reverse sorted). Data Structure: AVL Tree We have learned how to store values in a BST data structure that supports adding, removal, and searching in time Θ(h), where h is the height of the tree. We have also seen that in the worst case, the height can be Θ(n), the size of the tree. If we can keep the tree fairly balanced, then we can reduce the height to Θ(lg n) and obtain a fairly ecient data structure. To maintain a balanced structure we will use a technique invented by Adelson-Velskii and Landis (hence the name AVL tree). The idea is to keep a counter in every node (called a balance factor ) that measures the dierence between the heights of the left and right subtrees (right minus left). We will add the following added constraint on our BST ˆ No balance factor will be greater than 1 or less than. Any BST that satises this constraint will have Θ(lg n) height. Every time we add or remove a node we may violate this constraint. To return the tree to balance we will employ a technique called a rotation. Consider the following AVL tree: Each node has the value and balance factor in it. Now suppose we add 16 (just as we would in a BST). 4

5 As you can see, the tree now violates our constraints on the balance factors. To remedy the issue, we nd the closest (lowest) ancestor of the newly added node that is out of balance. In this case, it would be the node containing the 2. We then perform a rotation so that takes the place of 2, and 2 becomes the right child of. The resulting tree is Now the tree satises the constraint again. Let's generalize this example to all possible ways adding a node can imbalance the tree. First notice that if adding a value will cause a node to violate its balance factor constraint, then it must have been 1 or already, since adding a single node can add at most 1 to the height of any subtree. Let's assume a node currently has balance factor 1 and some value X. We will model the possible ways that the node containing X will be the lowest node that violates the balance factor constraint (by adding values).

6 X Y C k k A B k Above Y < X and all of the labeled subtrees have the same height k. The subtree rooted at X has height k + 1. We rst handle the case that a node is added to subtree A that increases its height. X -2 Z Y C k B k A 1 A 2 Here we assumed the value added was smaller than Y. Note that the subtree rooted at X now has height k + 2. We then zoom in on the subtree A by drawing its root Z and subtrees A 1 and A 2. The possible heights of A 1, A 2 are (this will not eect our course of action though): 1. If k = then A 1, A 2 are both empty. Z has a balance factor of 2. If k > and the new value is smaller than Z then A 1 has height k and A 2 has height k 1. Z has a balance factor of If k > and the new value is greater than Z then A 1 has height k 1 and A 2 has height k. Z has a balance factor of. To x this we perform a rotation that puts Y where X is: 6

7 Y Z X A 1 A 2 B C k The balance constraints are no longer violated. Note that the subtree rooted at Y has height k + 1, the same as the subtree rooted at X before a value was added. Thus all nodes above Y in the tree are now balanced as well. This is the so called left-left case since Z is the left child of Y which is the left child of X. The other left-right case occurs when we add a value that is larger than Y to our original tree (the picture with A, B, and C) above. Y W X -2 C k k A B 1 B 2 Here we have zoomed in on the subtree B. We have similar cases as above that determine the heights of B 1, B 2. Here we perform a rotation that puts W in place of Y : W X -2 Y C k B 2 k A B 1 This gives us a case like the left-left situation. Thus we perform a second rotation as above putting W in place of X: 7

8 W Y X k A B 1 B 2 C k Again we have restored balance and the resulting tree has height k + 1. Thus all ancestors of W are balanced too. Using the operations above and their reections (right-right and right-left cases) we can enforce the balance constraints on every add operation. The TreeMap and TreeSet in Java use a related data structure called a red-black tree that uses a slightly dierent constraint for balance, but also uses rotations to enforce the constraint. AVL Tree Exercises 1. Consider the following BST (a) Add balance factors to all of the nodes. (b) Show what happens when we add the node 13 (treating the tree as an AVL tree). (c) Next add 7 to the tree (treating the tree as an AVL tree). (d) ( ) Next delete, 7, and 6 from the tree. balance constraints. Make sure to remedy any violated 2. Give a simple Θ(n lg n) sorting algorithm assuming you have access to an AVL Tree data structure. 3. ( ) The AVL Tree deletion algorithm is similar to the addition algorithm, but can cause as many as Θ(h) rotations to occur where h is the height of the tree. Can you explain why? 4. ( ) Let minnodes(h) denote the minimum number of nodes you need to have an AVL- Tree of height h. For h >= 2 give a recurrence relation satised by minnodes(h). 8

9 . In the Priority Queue ADT elements have an ordering (Comparable or Comparator). When you dequeue an element, instead of removing the earliest added element, you remove the earliest element in the given ordering. You can imagine a situation where you are ordering tasks to work on, but each task has a priority governing when you must work on it. It has the following operations (a) add: Adds an element to the Priority Queue (b) dequeue: Removes the smallest element (with respect to the ordering) Describe an ecient implementation of this ADT. AVL Tree Solutions 1. (a) (b) We perform the left-right sequence of 2 rotations after adding (c) After adding 7 we perform the right-right rotation which is simply the reection of the left-left rotation. 9

10 (d) After the removal the root is unbalanced. We will treat this like the right-right case and rotate the 13 into the root Add all of the elements to the AVL Tree, then perform an inorder traversal. If we want to handle duplicates, we can either extend our AVL Tree/BST to allow duplicates, or instead of storing values, we can store lists of values that are equivalent with respect to the ordering. This method of sorting isn't used. 3. Note that after an add operation, our rotations returned the eected subtree to the same height it was before the add operation. Thus no ancestors above the lowest unbalanced node had to be xed. After a remove operation the eected subtree may have a lower height than before, and thus ancestors of the lowest unbalanced node may need to be xed as well. 4. minnodes(h) = 1 + minnodes(h 1) + minnodes(h 2). To see why, note that we must have a subtree of height h 1 so that the whole tree has height h. Secondly, the smallest we can make the other subtree is height h 2 due to the balance constraint. This can be used to show that minnodes grows faster than the Fibonacci sequence, which grows exponentially. This in turn can be used to show that the height of an AVL tree is Θ(lg n).. Use an AVL Tree. Adds simply add nodes to the tree. To dequeue we simply remove the smallest value. Both operations require Θ(lg n) in the worst-case. 1

11 Data Structure: (Binary) Min Heap Above we saw how to implement a PriorityQueue using an AVL Tree. Here we will give a new data structure that can be used to implement a PriorityQueue and is way more ecient in practice (lower constants embedded in the Θ-terms). We will allow duplicates values. A min heap is a binary tree with the following two constraints: 1. Ordering: Every node is equal to or smaller than its children. 2. Completenees: Every level of the tree is full but the last level. In the last level the nodes ll up the leftmost positions. The second constraint sounds odd, but it will enable a very ecient implementation. Instead of using binary tree nodes to store our values, we will just use an array containing all of the elements as they would appear in a level-by-level (breadth rst) traversal. Consider the following min heap: We then store this in an ArrayList The nice thing about this format is that we can easily nd the children and parent of any node. Suppose you are at the node with index k in the array. 1. Left child: 2k Right child: 2k Parent: (k 1)/2 (Java integer division; gives on root) We will justify the left child formula. The rest will follow from that. Note that level of nodes at depth d contains the indices 2 d 1 through 2 d 2. Thus the kth node in that level has index 2 d 1 + (k 1). Applying the left child formula, we obtain index 2(2 d 1 + (k 1)) + 1 = 2 d 1 + 2(k 1). This is the index in level d + 1 just after the 2(k 1) children of the nodes preceding our original node in level d. 11

12 The nice formulas above are made possible by the array storage format. Since our min heaps have the completeness property, the array format isn't wasteful. What remains is to implement the two main operations of the min heap: add and removemin. The key to all heap operations is to rst guarantee that the completeness property holds. After the shape is correct, we then make a few updates to x the ordering constraint. Suppose we want to add the node 1 to our heap above. We rst add 1 in the next available spot in the lowest level: Next we need to x the ordering constraint. We use an operation called sift-up. Take the newly added node an compare it with its parent. If it is smaller, swap, and repeat the process on the parent. This is depicted below To remove the mininum we rst swap the top value with the last value. Then we can safely remove the last value and maintain the shape. Finally, we correct the ordering constraint by checking if the root is bigger than its smallest child. If so, swap and then repeat on the node you swapped with. This process is sometimes called sift-down. Min Heap Exercises 1. Consider the following min heap (a) What is the index of 11 in the corresponding array? (b) Add an 8 to the min heap. (c) Then add a 1 to the min heap. (d) Then removemin from the min heap.

13 (e) Then removemin from the min heap. 2. A max heap is just like a min heap, but each node must be larger than its children. Explain why a max heap data structure is unnecessary if you already have a min heap. 3. What are the worst-case runtimes of add and removemin? 4. Assuming you have access to a min-heap, show how to sort a list of Comparable values in worst-case time Θ(n lg n).. How long does it take to nd a value in a min heap? 6. ( ) Sometimes it is useful to remove an arbitrary element from a min heap given its index. Explain how to do this in worst-case Θ(lg n) time. 7. ( ) Given an array of n comparable values, show how to turn it into a min heap. There is a Θ(n) worst-case implementation. Min Heap Solutions 1. (a) 4 (b) No sifting is required (c) Here we must sift-up performing 3 swaps (d) We swap the 7 into the root, remove the 1, and then sift-down (swap 7 with then 6)

14 (e) We swap the with the 8, remove the, and then sift-down (swap 8 with 6 then 7) Just use a min heap but reverse the ordering. 3. Both are Θ(lg n) since our tree is always well-balanced. 4. Add all elements to a min heap, and then repeatedly call removemin to pull them out in order. This is called Heapsort (better than our AVL Tree sorting algorithm above due to the low constant on all heap operations).. Θ(n) in the worst-case (consider a really large value that isn't in the heap) since the heap ordering property doesn't aid in searches like the BST property does. 6. We use the following steps. (a) Swap the item to be removed with the last item and then remove the last item. (b) The swap may have broken the ordering property so: i. Check if the swapped item is smaller than its parent. If so, do the sift-up procedure on it. ii. Otherwise, do the sift-down procedure on it. 7. The slow method is to just call add n times giving a worst-case Θ(n lg n) runtime. A better method is to loop backwards through the array and run the sift-down procedure on every value. To see why the runtime is Θ(n) we consider the work done by sift-down at every node. For simplicity, let's assume every level of the heap is full. Let the height of a node be the height of the subtree it is the root of. All nodes will require at most C steps to compare them with their children in the sift-down procedure. Nodes of height at least one will require at most an extra C steps, since they they could undergo a swap. Nodes of height at least two will require an extra C steps on top of that, and so forth. But, each time we increase the height we halve the number of nodes we consider. Since Cn + Cn/2 + Cn/4 + = 2Cn = Θ(n) the result follows. 14

Algorithms. AVL Tree

Algorithms. AVL Tree Algorithms AVL Tree Balanced binary tree The disadvantage of a binary search tree is that its height can be as large as N-1 This means that the time needed to perform insertion and deletion and many other

More information

Data Structures Brett Bernstein

Data Structures Brett Bernstein Data Structures Brett Bernstein Final Review 1. Consider a binary tree of height k. (a) What is the maximum number of nodes? (b) What is the maximum number of leaves? (c) What is the minimum number of

More information

Announcements. Midterm exam 2, Thursday, May 18. Today s topic: Binary trees (Ch. 8) Next topic: Priority queues and heaps. Break around 11:45am

Announcements. Midterm exam 2, Thursday, May 18. Today s topic: Binary trees (Ch. 8) Next topic: Priority queues and heaps. Break around 11:45am Announcements Midterm exam 2, Thursday, May 18 Closed book/notes but one sheet of paper allowed Covers up to stacks and queues Today s topic: Binary trees (Ch. 8) Next topic: Priority queues and heaps

More information

Binary heaps (chapters ) Leftist heaps

Binary heaps (chapters ) Leftist heaps Binary heaps (chapters 20.3 20.5) Leftist heaps Binary heaps are arrays! A binary heap is really implemented using an array! 8 18 29 20 28 39 66 Possible because of completeness property 37 26 76 32 74

More information

Hierarchical data structures. Announcements. Motivation for trees. Tree overview

Hierarchical data structures. Announcements. Motivation for trees. Tree overview Announcements Midterm exam 2, Thursday, May 18 Closed book/notes but one sheet of paper allowed Covers up to stacks and queues Today s topic: Binary trees (Ch. 8) Next topic: Priority queues and heaps

More information

DATA STRUCTURES AND ALGORITHMS. Hierarchical data structures: AVL tree, Bayer tree, Heap

DATA STRUCTURES AND ALGORITHMS. Hierarchical data structures: AVL tree, Bayer tree, Heap DATA STRUCTURES AND ALGORITHMS Hierarchical data structures: AVL tree, Bayer tree, Heap Summary of the previous lecture TREE is hierarchical (non linear) data structure Binary trees Definitions Full tree,

More information

9/29/2016. Chapter 4 Trees. Introduction. Terminology. Terminology. Terminology. Terminology

9/29/2016. Chapter 4 Trees. Introduction. Terminology. Terminology. Terminology. Terminology Introduction Chapter 4 Trees for large input, even linear access time may be prohibitive we need data structures that exhibit average running times closer to O(log N) binary search tree 2 Terminology recursive

More information

Introduction. for large input, even access time may be prohibitive we need data structures that exhibit times closer to O(log N) binary search tree

Introduction. for large input, even access time may be prohibitive we need data structures that exhibit times closer to O(log N) binary search tree Chapter 4 Trees 2 Introduction for large input, even access time may be prohibitive we need data structures that exhibit running times closer to O(log N) binary search tree 3 Terminology recursive definition

More information

3. Priority Queues. ADT Stack : LIFO. ADT Queue : FIFO. ADT Priority Queue : pick the element with the lowest (or highest) priority.

3. Priority Queues. ADT Stack : LIFO. ADT Queue : FIFO. ADT Priority Queue : pick the element with the lowest (or highest) priority. 3. Priority Queues 3. Priority Queues ADT Stack : LIFO. ADT Queue : FIFO. ADT Priority Queue : pick the element with the lowest (or highest) priority. Malek Mouhoub, CS340 Winter 2007 1 3. Priority Queues

More information

Part 2: Balanced Trees

Part 2: Balanced Trees Part 2: Balanced Trees 1 AVL Trees We could dene a perfectly balanced binary search tree with N nodes to be a complete binary search tree, one in which every level except the last is completely full. A

More information

Analysis of Algorithms

Analysis of Algorithms Analysis of Algorithms Trees-I Prof. Muhammad Saeed Tree Representation.. Analysis Of Algorithms 2 .. Tree Representation Analysis Of Algorithms 3 Nomenclature Nodes (13) Size (13) Degree of a node Depth

More information

CSC 421: Algorithm Design Analysis. Spring 2013

CSC 421: Algorithm Design Analysis. Spring 2013 CSC 421: Algorithm Design Analysis Spring 2013 Transform & conquer transform-and-conquer approach presorting balanced search trees, heaps Horner's Rule problem reduction 1 Transform & conquer the idea

More information

Priority Queues Heaps Heapsort

Priority Queues Heaps Heapsort Priority Queues Heaps Heapsort After this lesson, you should be able to apply the binary heap insertion and deletion algorithms by hand implement the binary heap insertion and deletion algorithms explain

More information

CS 240 Fall Mike Lam, Professor. Priority Queues and Heaps

CS 240 Fall Mike Lam, Professor. Priority Queues and Heaps CS 240 Fall 2015 Mike Lam, Professor Priority Queues and Heaps Priority Queues FIFO abstract data structure w/ priorities Always remove item with highest priority Store key (priority) with value Store

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

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

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs Computational Optimization ISE 407 Lecture 16 Dr. Ted Ralphs ISE 407 Lecture 16 1 References for Today s Lecture Required reading Sections 6.5-6.7 References CLRS Chapter 22 R. Sedgewick, Algorithms in

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 10: Search and Heaps MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Search and Heaps 2 Linear Search Binary Search Introduction to trees Priority Queues Heaps Linear Search

More information

Lecture 6: Analysis of Algorithms (CS )

Lecture 6: Analysis of Algorithms (CS ) Lecture 6: Analysis of Algorithms (CS583-002) Amarda Shehu October 08, 2014 1 Outline of Today s Class 2 Traversals Querying Insertion and Deletion Sorting with BSTs 3 Red-black Trees Height of a Red-black

More information

CMSC 341 Lecture 14: Priority Queues, Heaps

CMSC 341 Lecture 14: Priority Queues, Heaps CMSC 341 Lecture 14: Priority Queues, Heaps Prof. John Park Based on slides from previous iterations of this course Today s Topics Priority Queues Abstract Data Type Implementations of Priority Queues:

More information

Midterm solutions. n f 3 (n) = 3

Midterm solutions. n f 3 (n) = 3 Introduction to Computer Science 1, SE361 DGIST April 20, 2016 Professors Min-Soo Kim and Taesup Moon Midterm solutions Midterm solutions The midterm is a 1.5 hour exam (4:30pm 6:00pm). This is a closed

More information

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

Algorithms in Systems Engineering ISE 172. Lecture 16. Dr. Ted Ralphs Algorithms in Systems Engineering ISE 172 Lecture 16 Dr. Ted Ralphs ISE 172 Lecture 16 1 References for Today s Lecture Required reading Sections 6.5-6.7 References CLRS Chapter 22 R. Sedgewick, Algorithms

More information

Priority Queues and Heaps

Priority Queues and Heaps Priority Queues and Heaps Data Structures and Algorithms CSE 373 SU 18 BEN JONES 1 Warm Up We have seen several data structures that can implement the Dictionary ADT so far: Arrays, Binary (AVL) Trees,

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

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

Advanced Tree Data Structures

Advanced Tree Data Structures Advanced Tree Data Structures Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park Binary trees Traversal order Balance Rotation Multi-way trees Search Insert Overview

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 12: Heaps and Priority Queues MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Heaps and Priority Queues 2 Priority Queues Heaps Priority Queue 3 QueueADT Objects are added and

More information

CS2 Algorithms and Data Structures Note 6

CS2 Algorithms and Data Structures Note 6 CS Algorithms and Data Structures Note 6 Priority Queues and Heaps In this lecture, we will discuss another important ADT: PriorityQueue. Like stacks and queues, priority queues store arbitrary collections

More information

CS2 Algorithms and Data Structures Note 6

CS2 Algorithms and Data Structures Note 6 CS Algorithms and Data Structures Note 6 Priority Queues and Heaps In this lecture, we will discuss priority queues, another important ADT. As stacks and queues, priority queues store arbitrary collections

More information

AVL Trees Heaps And Complexity

AVL Trees Heaps And Complexity AVL Trees Heaps And Complexity D. Thiebaut CSC212 Fall 14 Some material taken from http://cseweb.ucsd.edu/~kube/cls/0/lectures/lec4.avl/lec4.pdf Complexity Of BST Operations or "Why Should We Use BST Data

More information

Priority Queues and Heaps. Heaps of fun, for everyone!

Priority Queues and Heaps. Heaps of fun, for everyone! Priority Queues and Heaps Heaps of fun, for everyone! Learning Goals After this unit, you should be able to... Provide examples of appropriate applications for priority queues and heaps Manipulate data

More information

Data Structures Brett Bernstein

Data Structures Brett Bernstein Data Structures Brett Bernstein Lecture Review Exercises. Given sorted lists, return the number of elements they have in common. public static int numshared(int[] a, int[] b). Given sorted lists, return

More information

9. Heap : Priority Queue

9. Heap : Priority Queue 9. Heap : Priority Queue Where We Are? Array Linked list Stack Queue Tree Binary Tree Heap Binary Search Tree Priority Queue Queue Queue operation is based on the order of arrivals of elements FIFO(First-In

More information

Lecture 7. Transform-and-Conquer

Lecture 7. Transform-and-Conquer Lecture 7 Transform-and-Conquer 6-1 Transform and Conquer This group of techniques solves a problem by a transformation to a simpler/more convenient instance of the same problem (instance simplification)

More information

Lecture 9: Balanced Binary Search Trees, Priority Queues, Heaps, Binary Trees for Compression, General Trees

Lecture 9: Balanced Binary Search Trees, Priority Queues, Heaps, Binary Trees for Compression, General Trees Lecture 9: Balanced Binary Search Trees, Priority Queues, Heaps, Binary Trees for Compression, General Trees Reading materials Dale, Joyce, Weems: 9.1, 9.2, 8.8 Liang: 26 (comprehensive edition) OpenDSA:

More information

COMP : Trees. COMP20012 Trees 219

COMP : Trees. COMP20012 Trees 219 COMP20012 3: Trees COMP20012 Trees 219 Trees Seen lots of examples. Parse Trees Decision Trees Search Trees Family Trees Hierarchical Structures Management Directories COMP20012 Trees 220 Trees have natural

More information

Algorithms and Data Structures

Algorithms and Data Structures Algorithms and Data Structures Dr. Malek Mouhoub Department of Computer Science University of Regina Fall 2002 Malek Mouhoub, CS3620 Fall 2002 1 6. Priority Queues 6. Priority Queues ffl ADT Stack : LIFO.

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

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

Computer Science 210 Data Structures Siena College Fall Topic Notes: Priority Queues and Heaps

Computer Science 210 Data Structures Siena College Fall Topic Notes: Priority Queues and Heaps Computer Science 0 Data Structures Siena College Fall 08 Topic Notes: Priority Queues and Heaps Heaps and Priority Queues From here, we will look at some ways that trees are used in other structures. First,

More information

Sorting and Searching

Sorting and Searching Sorting and Searching Lecture 2: Priority Queues, Heaps, and Heapsort Lecture 2: Priority Queues, Heaps, and Heapsort Sorting and Searching 1 / 24 Priority Queue: Motivating Example 3 jobs have been submitted

More information

Lecture 5: Sorting Part A

Lecture 5: Sorting Part A Lecture 5: Sorting Part A Heapsort Running time O(n lg n), like merge sort Sorts in place (as insertion sort), only constant number of array elements are stored outside the input array at any time Combines

More information

COMP Analysis of Algorithms & Data Structures

COMP Analysis of Algorithms & Data Structures COMP 3170 - Analysis of Algorithms & Data Structures Shahin Kamali Lecture 9 - Jan. 22, 2018 CLRS 12.2, 12.3, 13.2, read problem 13-3 University of Manitoba COMP 3170 - Analysis of Algorithms & Data Structures

More information

Trees. A tree is a directed graph with the property

Trees. A tree is a directed graph with the property 2: Trees Trees A tree is a directed graph with the property There is one node (the root) from which all other nodes can be reached by exactly one path. Seen lots of examples. Parse Trees Decision Trees

More information

Thus, it is reasonable to compare binary search trees and binary heaps as is shown in Table 1.

Thus, it is reasonable to compare binary search trees and binary heaps as is shown in Table 1. 7.2 Binary Min-Heaps A heap is a tree-based structure, but it doesn t use the binary-search differentiation between the left and right sub-trees to create a linear ordering. Instead, a binary heap only

More information

Trees. Reading: Weiss, Chapter 4. Cpt S 223, Fall 2007 Copyright: Washington State University

Trees. Reading: Weiss, Chapter 4. Cpt S 223, Fall 2007 Copyright: Washington State University Trees Reading: Weiss, Chapter 4 1 Generic Rooted Trees 2 Terms Node, Edge Internal node Root Leaf Child Sibling Descendant Ancestor 3 Tree Representations n-ary trees Each internal node can have at most

More information

Operations on Heap Tree The major operations required to be performed on a heap tree are Insertion, Deletion, and Merging.

Operations on Heap Tree The major operations required to be performed on a heap tree are Insertion, Deletion, and Merging. Priority Queue, Heap and Heap Sort In this time, we will study Priority queue, heap and heap sort. Heap is a data structure, which permits one to insert elements into a set and also to find the largest

More information

Computer Science 210 Data Structures Siena College Fall Topic Notes: Binary Search Trees

Computer Science 210 Data Structures Siena College Fall Topic Notes: Binary Search Trees Computer Science 10 Data Structures Siena College Fall 018 Topic Notes: Binary Search Trees Possibly the most common usage of a binary tree is to store data for quick retrieval. Definition: A binary tree

More information

CSC 321: Data Structures. Fall 2016

CSC 321: Data Structures. Fall 2016 CSC 321: Data Structures Fall 2016 Balanced and other trees balanced BSTs: AVL trees, red-black trees TreeSet & TreeMap implementations heaps priority queue implementation heap sort 1 Balancing trees recall:

More information

CSC 321: Data Structures. Fall 2017

CSC 321: Data Structures. Fall 2017 CSC 321: Data Structures Fall 2017 Balanced and other trees balanced BSTs: AVL trees, red-black trees TreeSet & TreeMap implementations heaps priority queue implementation heap sort 1 Balancing trees recall:

More information

COMP Analysis of Algorithms & Data Structures

COMP Analysis of Algorithms & Data Structures COMP 3170 - Analysis of Algorithms & Data Structures Shahin Kamali Lecture 9 - Jan. 22, 2018 CLRS 12.2, 12.3, 13.2, read problem 13-3 University of Manitoba 1 / 12 Binary Search Trees (review) Structure

More information

Lecture: Analysis of Algorithms (CS )

Lecture: Analysis of Algorithms (CS ) Lecture: Analysis of Algorithms (CS583-002) Amarda Shehu Fall 2017 1 Binary Search Trees Traversals, Querying, Insertion, and Deletion Sorting with BSTs 2 Example: Red-black Trees Height of a Red-black

More information

Section 4 SOLUTION: AVL Trees & B-Trees

Section 4 SOLUTION: AVL Trees & B-Trees Section 4 SOLUTION: AVL Trees & B-Trees 1. What 3 properties must an AVL tree have? a. Be a binary tree b. Have Binary Search Tree ordering property (left children < parent, right children > parent) c.

More information

CSE 373: AVL trees. Michael Lee Friday, Jan 19, 2018

CSE 373: AVL trees. Michael Lee Friday, Jan 19, 2018 CSE 373: AVL trees Michael Lee Friday, Jan 19, 2018 1 Warmup Warmup: What is an invariant? What are the AVL tree invariants, exactly? Discuss with your neighbor. 2 AVL Trees: Invariants Core idea: add

More information

Priority Queues and Binary Heaps

Priority Queues and Binary Heaps Yufei Tao ITEE University of Queensland In this lecture, we will learn our first tree data structure called the binary heap which serves as an implementation of the priority queue. Priority Queue A priority

More information

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS T E W H A R E W Ā N A N G A O T E Student ID:....................... Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2015 TRIMESTER 2 COMP103 INTRODUCTION

More information

CH 8. HEAPS AND PRIORITY QUEUES

CH 8. HEAPS AND PRIORITY QUEUES CH 8. HEAPS AND PRIORITY QUEUES ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY 2004) AND SLIDES FROM NANCY

More information

CMSC 341 Priority Queues & Heaps. Based on slides from previous iterations of this course

CMSC 341 Priority Queues & Heaps. Based on slides from previous iterations of this course CMSC 341 Priority Queues & Heaps Based on slides from previous iterations of this course Today s Topics Priority Queues Abstract Data Type Implementations of Priority Queues: Lists BSTs Heaps Heaps Properties

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

Basic Data Structures (Version 7) Name:

Basic Data Structures (Version 7) Name: Prerequisite Concepts for Analysis of Algorithms Basic Data Structures (Version 7) Name: Email: Concept: mathematics notation 1. log 2 n is: Code: 21481 (A) o(log 10 n) (B) ω(log 10 n) (C) Θ(log 10 n)

More information

Sorting and Searching

Sorting and Searching Sorting and Searching Lecture 2: Priority Queues, Heaps, and Heapsort Lecture 2: Priority Queues, Heaps, and Heapsort Sorting and Searching 1 / 24 Priority Queue: Motivating Example 3 jobs have been submitted

More information

Binary search trees (chapters )

Binary search trees (chapters ) Binary search trees (chapters 18.1 18.3) Binary search trees In a binary search tree (BST), every node is greater than all its left descendants, and less than all its right descendants (recall that this

More information

Heaps. 2/13/2006 Heaps 1

Heaps. 2/13/2006 Heaps 1 Heaps /13/00 Heaps 1 Outline and Reading What is a heap ( 8.3.1) Height of a heap ( 8.3.) Insertion ( 8.3.3) Removal ( 8.3.3) Heap-sort ( 8.3.) Arraylist-based implementation ( 8.3.) Bottom-up construction

More information

Binary Search Trees. Analysis of Algorithms

Binary Search Trees. Analysis of Algorithms Binary Search Trees Analysis of Algorithms Binary Search Trees A BST is a binary tree in symmetric order 31 Each node has a key and every node s key is: 19 23 25 35 38 40 larger than all keys in its left

More information

COMP171. AVL-Trees (Part 1)

COMP171. AVL-Trees (Part 1) COMP11 AVL-Trees (Part 1) AVL Trees / Slide 2 Data, a set of elements Data structure, a structured set of elements, linear, tree, graph, Linear: a sequence of elements, array, linked lists Tree: nested

More information

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17 01.433/33 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/2/1.1 Introduction In this lecture we ll talk about a useful abstraction, priority queues, which are

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

CH. 8 PRIORITY QUEUES AND HEAPS

CH. 8 PRIORITY QUEUES AND HEAPS CH. 8 PRIORITY QUEUES AND HEAPS ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY 2004) AND SLIDES FROM NANCY

More information

Chapter 2: Basic Data Structures

Chapter 2: Basic Data Structures Chapter 2: Basic Data Structures Basic Data Structures Stacks Queues Vectors, Linked Lists Trees (Including Balanced Trees) Priority Queues and Heaps Dictionaries and Hash Tables Spring 2014 CS 315 2 Two

More information

Self-Balancing Search Trees. Chapter 11

Self-Balancing Search Trees. Chapter 11 Self-Balancing Search Trees Chapter 11 Chapter Objectives To understand the impact that balance has on the performance of binary search trees To learn about the AVL tree for storing and maintaining a binary

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms CS245-2008S-19 B-Trees David Galles Department of Computer Science University of San Francisco 19-0: Indexing Operations: Add an element Remove an element Find an element,

More information

Queues. ADT description Implementations. October 03, 2017 Cinda Heeren / Geoffrey Tien 1

Queues. ADT description Implementations. October 03, 2017 Cinda Heeren / Geoffrey Tien 1 Queues ADT description Implementations Cinda Heeren / Geoffrey Tien 1 Queues Assume that we want to store data for a print queue for a student printer Student ID Time File name The printer is to be assigned

More information

Quiz 1 Solutions. (a) f(n) = n g(n) = log n Circle all that apply: f = O(g) f = Θ(g) f = Ω(g)

Quiz 1 Solutions. (a) f(n) = n g(n) = log n Circle all that apply: f = O(g) f = Θ(g) f = Ω(g) Introduction to Algorithms March 11, 2009 Massachusetts Institute of Technology 6.006 Spring 2009 Professors Sivan Toledo and Alan Edelman Quiz 1 Solutions Problem 1. Quiz 1 Solutions Asymptotic orders

More information

CS 234. Module 8. November 15, CS 234 Module 8 ADT Priority Queue 1 / 22

CS 234. Module 8. November 15, CS 234 Module 8 ADT Priority Queue 1 / 22 CS 234 Module 8 November 15, 2018 CS 234 Module 8 ADT Priority Queue 1 / 22 ADT Priority Queue Data: (key, element pairs) where keys are orderable but not necessarily distinct, and elements are any data.

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

ECE 242 Data Structures and Algorithms. Heaps I. Lecture 22. Prof. Eric Polizzi

ECE 242 Data Structures and Algorithms.  Heaps I. Lecture 22. Prof. Eric Polizzi ECE 242 Data Structures and Algorithms http://www.ecs.umass.edu/~polizzi/teaching/ece242/ Heaps I Lecture 22 Prof. Eric Polizzi Motivations Review of priority queue Input F E D B A Output Input Data structure

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms CS245-2017S-06 Binary Search Trees David Galles Department of Computer Science University of San Francisco 06-0: Ordered List ADT Operations: Insert an element in the list

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms Spring 2017-2018 Outline 1 Priority Queues Outline Priority Queues 1 Priority Queues Jumping the Queue Priority Queues In normal queue, the mode of selection is first in,

More information

12 Abstract Data Types

12 Abstract Data Types 12 Abstract Data Types 12.1 Foundations of Computer Science Cengage Learning Objectives After studying this chapter, the student should be able to: Define the concept of an abstract data type (ADT). Define

More information

COMP 103 RECAP-TODAY. Priority Queues and Heaps. Queues and Priority Queues 3 Queues: Oldest out first

COMP 103 RECAP-TODAY. Priority Queues and Heaps. Queues and Priority Queues 3 Queues: Oldest out first COMP 0 Priority Queues and Heaps RECAP RECAP-TODAY Tree Structures (in particular Binary Search Trees (BST)) BSTs idea nice way to implement a Set, Bag, or Map TODAY Priority Queue = variation on Queue

More information

Priority Queues, Binary Heaps, and Heapsort

Priority Queues, Binary Heaps, and Heapsort Priority Queues, Binary eaps, and eapsort Learning Goals: Provide examples of appropriate applications for priority queues and heaps. Implement and manipulate a heap using an array as the underlying data

More information

EXAMINATIONS 2016 TRIMESTER 2

EXAMINATIONS 2016 TRIMESTER 2 T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2016 TRIMESTER 2 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

More information

Binary search trees (chapters )

Binary search trees (chapters ) Binary search trees (chapters 18.1 18.3) Binary search trees In a binary search tree (BST), every node is greater than all its left descendants, and less than all its right descendants (recall that this

More information

AVL trees and rotations

AVL trees and rotations / AVL trees and rotations This week, you should be able to perform rotations on height-balanced trees, on paper and in code write a rotate() method search for the kth item in-order using rank } Term project

More information

COMP Analysis of Algorithms & Data Structures

COMP Analysis of Algorithms & Data Structures COMP 3170 - Analysis of Algorithms & Data Structures Shahin Kamali Binary Search Trees CLRS 12.2, 12.3, 13.2, read problem 13-3 University of Manitoba COMP 3170 - Analysis of Algorithms & Data Structures

More information

CSE373: Data Structures & Algorithms Lecture 9: Priority Queues and Binary Heaps. Linda Shapiro Spring 2016

CSE373: Data Structures & Algorithms Lecture 9: Priority Queues and Binary Heaps. Linda Shapiro Spring 2016 CSE373: Data Structures & Algorithms Lecture : Priority Queues and Binary Heaps Linda Shapiro Spring 2016 A new ADT: Priority Queue A priority queue holds compare-able data Like dictionaries, we need to

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

CSCI 136 Data Structures & Advanced Programming. Lecture 22 Fall 2018 Instructor: Bills

CSCI 136 Data Structures & Advanced Programming. Lecture 22 Fall 2018 Instructor: Bills CSCI 136 Data Structures & Advanced Programming Lecture 22 Fall 2018 Instructor: Bills Last Time Lab 7: Two Towers Array Representations of (Binary) Trees Application: Huffman Encoding 2 Today Improving

More information

AVL Tree Definition. An example of an AVL tree where the heights are shown next to the nodes. Adelson-Velsky and Landis

AVL Tree Definition. An example of an AVL tree where the heights are shown next to the nodes. Adelson-Velsky and Landis Presentation for use with the textbook Data Structures and Algorithms in Java, 6 th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 0 AVL Trees v 6 3 8 z 0 Goodrich, Tamassia, Goldwasser

More information

Summer Final Exam Review Session August 5, 2009

Summer Final Exam Review Session August 5, 2009 15-111 Summer 2 2009 Final Exam Review Session August 5, 2009 Exam Notes The exam is from 10:30 to 1:30 PM in Wean Hall 5419A. The exam will be primarily conceptual. The major emphasis is on understanding

More information

Priority Queues Heaps Heapsort

Priority Queues Heaps Heapsort Priority Queues Heaps Heapsort Complete the Doublets partner(s) evaluation by tonight. Use your individual log to give them useful feedback! Like 230 and have workstudy funding? We are looking for CSSE230

More information

CSC Design and Analysis of Algorithms. Lecture 8. Transform and Conquer II Algorithm Design Technique. Transform and Conquer

CSC Design and Analysis of Algorithms. Lecture 8. Transform and Conquer II Algorithm Design Technique. Transform and Conquer CSC 301- Design and Analysis of Algorithms Lecture Transform and Conquer II Algorithm Design Technique Transform and Conquer This group of techniques solves a problem by a transformation to a simpler/more

More information

Advanced Set Representation Methods

Advanced Set Representation Methods Advanced Set Representation Methods AVL trees. 2-3(-4) Trees. Union-Find Set ADT DSA - lecture 4 - T.U.Cluj-Napoca - M. Joldos 1 Advanced Set Representation. AVL Trees Problem with BSTs: worst case operation

More information

Data Structures Question Bank Multiple Choice

Data Structures Question Bank Multiple Choice Section 1. Fundamentals: Complexity, Algorthm Analysis 1. An algorithm solves A single problem or function Multiple problems or functions Has a single programming language implementation 2. A solution

More information

ADVANCED DATA STRUCTURES STUDY NOTES. The left subtree of each node contains values that are smaller than the value in the given node.

ADVANCED DATA STRUCTURES STUDY NOTES. The left subtree of each node contains values that are smaller than the value in the given node. UNIT 2 TREE STRUCTURES ADVANCED DATA STRUCTURES STUDY NOTES Binary Search Trees- AVL Trees- Red-Black Trees- B-Trees-Splay Trees. HEAP STRUCTURES: Min/Max heaps- Leftist Heaps- Binomial Heaps- Fibonacci

More information

CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators)

CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators) Name: Email address: Quiz Section: CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators) Instructions: Read the directions for each question carefully before answering. We will

More information

Solutions. Suppose we insert all elements of U into the table, and let n(b) be the number of elements of U that hash to bucket b. Then.

Solutions. Suppose we insert all elements of U into the table, and let n(b) be the number of elements of U that hash to bucket b. Then. Assignment 3 1. Exercise [11.2-3 on p. 229] Modify hashing by chaining (i.e., bucketvector with BucketType = List) so that BucketType = OrderedList. How is the runtime of search, insert, and remove affected?

More information

Inf 2B: AVL Trees. Lecture 5 of ADS thread. Kyriakos Kalorkoti. School of Informatics University of Edinburgh

Inf 2B: AVL Trees. Lecture 5 of ADS thread. Kyriakos Kalorkoti. School of Informatics University of Edinburgh Inf 2B: AVL Trees Lecture 5 of ADS thread Kyriakos Kalorkoti School of Informatics University of Edinburgh Dictionaries A Dictionary stores key element pairs, called items. Several elements might have

More information

CSE 2123: Collections: Priority Queues. Jeremy Morris

CSE 2123: Collections: Priority Queues. Jeremy Morris CSE 2123: Collections: Priority Queues Jeremy Morris 1 Collections Priority Queue Recall: A queue is a specific type of collection Keeps elements in a particular order We ve seen two examples FIFO queues

More information

CSE2331/5331. Topic 6: Binary Search Tree. Data structure Operations CSE 2331/5331

CSE2331/5331. Topic 6: Binary Search Tree. Data structure Operations CSE 2331/5331 CSE2331/5331 Topic 6: Binary Search Tree Data structure Operations Set Operations Maximum Extract-Max Insert Increase-key We can use priority queue (implemented by heap) Search Delete Successor Predecessor

More information

Properties of a heap (represented by an array A)

Properties of a heap (represented by an array A) Chapter 6. HeapSort Sorting Problem Input: A sequence of n numbers < a1, a2,..., an > Output: A permutation (reordering) of the input sequence such that ' ' ' < a a a > 1 2... n HeapSort O(n lg n) worst

More information