1 CompSci 105 SS 2006 Principles of Computer Science Lecture 17: Heaps cont.

Slides:



Advertisements
Similar presentations
Splay Trees CSE 331 Section 2 James Daly. Reminder Homework 2 is out Due Thursday in class Project 2 is out Covers tree sets Due next Friday at midnight.
Advertisements

COL 106 Shweta Agrawal and Amit Kumar
Trees Types and Operations
Time Complexity of Basic BST Operations Search, Insert, Delete – These operations visit the nodes along a root-to- leaf path – The number of nodes encountered.
AVL Trees CS II – Fall /8/2010. Announcements HW#2 is posted – Uses AVL Trees, so you have to implement an AVL Tree class. Most of the code is provided.
Data Structures Michael J. Watts
1 AVL Trees Drozdek Section pages
AA Trees another alternative to AVL trees. Balanced Binary Search Trees A Binary Search Tree (BST) of N nodes is balanced if height is in O(log N) A balanced.
Balanced Search Trees. 2-3 Trees Trees Red-Black Trees AVL Trees.
InOrder Traversal Algorithm // InOrder traversal algorithm inOrder(TreeNode n) { if (n != null) { inOrder(n.getLeft()); visit(n) inOrder(n.getRight());
4.5 AVL Trees  A tree is said to be balanced if for each node, the number of nodes in the left subtree and the number of nodes in the right subtree differ.
CSE332: Data Abstractions Lecture 7: AVL Trees Tyler Robison Summer
CMPT 225 Priority Queues and Heaps. Priority Queues Items in a priority queue have a priority The priority is usually numerical value Could be lowest.
Binary Heaps CSE 373 Data Structures Lecture 11. 2/5/03Binary Heaps - Lecture 112 Readings Reading ›Sections
1 Balanced Search Trees  several varieties  AVL trees  trees  Red-Black trees  B-Trees (used for searching secondary memory)  nodes are added.
CSC 213 Lecture 7: Binary, AVL, and Splay Trees. Binary Search Trees (§ 9.1) Binary search tree (BST) is a binary tree storing key- value pairs (entries):
CSC 212 Lecture 19: Splay Trees, (2,4) Trees, and Red-Black Trees.
1 CSE 326: Data Structures Trees Lecture 7: Wednesday, Jan 23, 2003.
1 BST Trees A binary search tree is a binary tree in which every node satisfies the following: the key of every node in the left subtree is.
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
INTRODUCTION TO AVL TREES P. 839 – 854. INTRO  Review of Binary Trees: –Binary Trees are useful for quick retrieval of items stored in the tree –order.
Compiled by: Dr. Mohammad Alhawarat BST, Priority Queue, Heaps - Heapsort CHAPTER 07.
BINARY SEARCH TREE. Binary Trees A binary tree is a tree in which no node can have more than two children. In this case we can keep direct links to the.
Course: Programming II - Abstract Data Types Red-Black TreesSlide Number 1 Balanced Search Trees Binary Search Tree data structures can allow insertion,
1 Binary Trees Informal defn: each node has 0, 1, or 2 children Informal defn: each node has 0, 1, or 2 children Formal defn: a binary tree is a structure.
AVL Trees. Knowing More How many nodes? – Determine on demand.
Search Trees Chapter   . Outline  Binary Search Trees  AVL Trees  Splay Trees.
Binary trees -2 Chapter Threaded trees (depth first) Binary trees have a lot of wasted space: the leaf nodes each have 2 null pointers We can.
11/7/20151 Balanced Trees Data Structures Ananda Gunawardena.
COSC2007 Data Structures II Chapter 12 Tables & Priority Queues III.
1 Joe Meehean.  We wanted a data structure that gave us... the smallest item then the next smallest then the next and so on…  This ADT is called a priority.
Oct 26, 2001CSE 373, Autumn A Forest of Trees Binary search trees: simple. –good on average: O(log n) –bad in the worst case: O(n) AVL trees: more.
Chapter 19: Binary Search Trees or How I Learned to Love AVL Trees and Balance The Tree Group 6: Tim Munn.
Binary Search Trees (BSTs) 18 February Binary Search Tree (BST) An important special kind of binary tree is the BST Each node stores some information.
Lecture 15 Jianjun Hu Department of Computer Science and Engineering University of South Carolina CSCE350 Algorithms and Data Structure.
1 Lecture 21: Binary Search Tree delete etc. operations Lecturer: Santokh Singh CompSci 105 SS 2005 Principles of Computer Science.
CIS 068 Welcome to CIS 068 ! Lesson 12: Data Structures 3 Trees.
IT 60101: Lecture #121 Foundation of Computing Systems Lecture 12 Trees: Part VII.
COSC 2007 Data Structures II Chapter 13 Advanced Implementation of Tables I.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
AVL Trees and Heaps. AVL Trees So far balancing the tree was done globally Basically every node was involved in the balance operation Tree balancing can.
1 CSC TREES AVL & BALANCED TREES. 2 Balanced Trees The advantage of balanced trees is that we can perform most operation in time proportional to.
CSE373: Data Structures & Algorithms Lecture 7: AVL Trees Linda Shapiro Winter 2015.
Lecture 10COMPSCI.220.FS.T Binary Search Tree BST converts a static binary search into a dynamic binary search allowing to efficiently insert and.
AVL Trees 1. Balancing a BST Goal – Keep the height small – For any node, left and right sub-tree have approximately the same height Ensures fast (O(lgn))
CS 5243: Algorithms Balanced Trees AVL : Adelson-Velskii and Landis(1962)
CS 367 Introduction to Data Structures Lecture 8.
AVL TREES By Asami Enomoto CS 146 AVL Tree is… named after Adelson-Velskii and Landis the first dynamically balanced trees to be propose Binary search.
2 Binary Heaps What if we’re mostly concerned with finding the most relevant data?  A binary heap is a binary tree (2 or fewer subtrees for each node)
CSE373: Data Structures & Algorithms Lecture 8: AVL Trees and Priority Queues Catie Baker Spring 2015.
Course: Programming II - Abstract Data Types HeapsSlide Number 1 The ADT Heap So far we have seen the following sorting types : 1) Linked List sort by.
AVL Trees AVL (Adel`son-Vel`skii and Landis) tree = – A BST – With the property: For every node, the heights of the left and right subtrees differ at most.
Red-Black Trees an alternative to AVL trees. Balanced Binary Search Trees A Binary Search Tree (BST) of N nodes is balanced if height is in O(log N) A.
Balancing Binary Search Trees. Balanced Binary Search Trees A BST is perfectly balanced if, for every node, the difference between the number of nodes.
COSC 2007 Data Structures II Chapter 13 Advanced Implementation of Tables II.
AA Trees.
BCA-II Data Structure Using C
BST Trees
Introduction Applications Balance Factor Rotations Deletion Example
AVL Tree Mohammad Asad Abbasi Lecture 12
Lecture 22 Binary Search Trees Chapter 10 of textbook
Lecture 25 Splay Tree Chapter 10 of textbook
AVL Trees: AVL Trees: Balanced binary search tree
Search Sorted Array: Binary Search Linked List: Linear Search
AVL Trees Lab 11: AVL Trees.
Lecture 9: Self Balancing Trees
AVL Tree By Rajanikanth B.
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
AVL Trees: AVL Trees: Balanced binary search tree
Presentation transcript:

1 CompSci 105 SS 2006 Principles of Computer Science Lecture 17: Heaps cont.

2 An Aside: Iterators Quite often we want to get data in a certain order We want the data to come one at a time at our leisure We do not care how it gets the data, as long as it is in the order we expect

3 An Aside: Iterators The Iterator interface abstracts this concept for us Interface: Iterator boolean hasNext() Object next() void remove() (optional)

4 An Aside: Iterators Writing an Iterator is simple Mostly return these from various methods e.g. BST public Iterator getPostOrderTraversal(){...} -or- public static Iterator getPreOrderTraversal(BinaryTree b){...}

5 An Aside: Iterators How the Iterator arrives at the next node is completely up to the writer The user has no idea Turns any data structure into a sorted list

6 Heap Implementation U J G Q MB As a tree

7 Binary Trees in Arrays? M Q UO G JB As a tree

8 Binary Trees in Arrays! M Q UO G JB M 1G 2Q 3B 4J 5O 6U As a tree As an array

9 Other Implementations of Trees Multiple array implementation –Easy –left and right child references are indices to array –Does not require following object references

10 Array implementation 0U12 1Q34 2J5 3B 4M 5G 6 U J G Q MB

11 Other Implementations of Trees Single array implementation –most memory and speed efficient –Does not require references (i.e. compatible with almost all languages) –tree is stored in level order in array –“Missing” children are null –Use formulae to find children or parent...

12 Array implementation Given node at index ‘i’ in the array... parentIndex = (i-1)/2; rightChild = 2*i+1; leftChild= 2*i+2; 0U 1Q 2J 3B 4M 5G 6null U J G Q MB

13 Heap Delete Operation Retrieves and then deletes a Heap’s root item –Return the item in the root –Produce a semi-heap –Transform the semi-heap into a Heap

14 Return the item in the root Produce a semi-heap Transform the semi-heap into a Heap

15 Return the item in the root Produce a semi-heap Transform the semi-heap into a Heap

16 Return the item in the root Produce a semi-heap Transform the semi-heap into a Heap –Allows the item in the root to trickle down to its right place –Compare the search key in the root with that of its children's –Swap the item in the root with that of the larger child

17 Transform the semi-heap into a Heap –Allows the item in the root to trickle down to its right place –Compare the search key in the root with that of its children's –Swap the item in the root with that of the larger child

18 Heap Insert Operation Insert a new item into a Heap –New item is inserted at the bottom of the tree –Then it trickled up to its proper place Compare the search key in current node with that of its parent Swap the current node with its parent, if the current node has greater value The efficiency of a Heap Insert and Heap Delete is O(log n)

19 Heap Insert Operation

20 Heap insert heap[size] = newItem; child=size; parent=(size-1)/2; while ( parent>=0 && heap[child]>heap[parent] ) { temp = heap[parent] ; heap[parent] = heap[child] ; heap[child] = temp ; child=parent; parent=(parent-1)/2; } 0U 1Q 2J 3B 4M 5G 6 size = 6 newItem = K

21 Heaps remain complete and efficient BST’s may not BUT – Heaps have restrictions on use How to make BST more balanced without restricting its use? Back to Trees

22 Balanced Trees Obviously need to sacrifice some efficiency to keep balanced But if can guarantee tree is balanced, make search very efficient Two methods: –Splay Trees –AVL trees

23 Tree Rotations A rotation replaces the root of a subtree with one of its children. Rotation is an important operation for maintaining the balance of a Binary Search Tree.

24 Rotations Note that rotation operation can make certain children “parentless” These children/subtrees must be inserted into tree at appropriate locations

25 TreeNode rotateRight(TreeNode p) { if (p == null) return null; else if (p.getLeft() == null) return p; else { TreeNode newRoot = p.getLeft(); p.setLeft(newRoot.getRight()); newRoot.setRight(p); return newRoot;} } Question: Why can X’s child, B, always be made P’s left child??

26 Left Rotation??? Homework exercise...

27 Splay Trees A Splay Tree is a BST that rearranges its nodes during the access of nodes Splay – whenever a node is added, removed or retrieved, move the referenced node to become the new root of the Tree –In the case of removal, splay the tree around the parent node The average depth of those nodes to the root is halved, more close to the top of the tree and more efficiently accessed Can guarantee the O(log 2 n) performance

28 Splaying a node Case 0: If x is the root, we are done. Case 1: If x is a left/right child of the root, rotate the tree to the right/left about the root. x becomes the root and we are done. Case 2a: If x is the left child of its parent p, and p is the left child of its grandparent g, rotate first right about g, followed by a right rotation about p. This is called a double-right rotation. If x is the right child of a right child perform a double-left rotation. After the double rotation, continue splay at x in the new tree. Case 2b: If x is the right child of its parent p, and p is the left child of its grandparent g, we rotate first left around p and then right around g. This is called a left- right double rotation. If x is the left child of a right child perform a right-left double rotation. After the double rotation, continue splay at x in the new tree.

29 Splaying a node Case 1: The parent of x is root =>perform a single rotation

30 Splaying a node Case 2a: The parent of x is not the root and it is the left (right) child of a left(right) child => perform a double-right (double-left) rotation

31 Splaying a node Case 2b: The parent of x is not the root and it is the left (right) child of a right (left) child => perform a right-left (left-right) double rotation

32 Splaying a node Example: Splay the tree around node 5

33 Intuitive method... Always rotate node toward the root.

34 Efficiency?? What is the efficiency of splaying a node to the root? How often will this happen?

35 AVL Trees The AVL tree is named after its two inventors, G.M. Adelson-Velsky and E.M. Landis Keeps a BST tree mostly balanced so that all operations remain O(log 2 n)

36 AVL Trees An AVL Tree is a Binary Search Tree that the heights of the left and right subtrees of any node differ by no more than 1 : | HeightLeft – HeightRight | ≤1 Operations on an AVL tree is almost as efficiently as a minimum-height Binary Search Tree After each insert or delete, check whether the tree is still an AVL Tree; if not, restore the property by tree rotations

37 Efficiency?? What is the efficiency of checking the height of the left and right subtree of the root of a tree?? How often will this happen?

38

39 Rotations to obtain AVL property Case 0: No rotation needed Case 1: Single rotation to the Left (Right) to obtain a balanced shape Case 2: Double Right-Left (Left-Right) rotation to obtain a balanced shape

40 Rotations to obtain AVL property Case 0: No rotation needed

41 Rotations to obtain AVL property Case 1: Single rotation to the Left (Right) to obtain a balanced shape

42 Rotations to obtain AVL property Case 2: Double Right-Left (Left-Right) rotation to obtain a balanced shape

43 Comparison Splay Trees Slowest Average=worst=best Commonly accessed nodes near root All operations need rotation AVL Trees Trade off between two Average=worst=best Nodes randomly distributed Only some add/delete need rotation BST Trees Fastest if balanced, otherwise slowest Average!=worst!=best Nodes randomly distributed No rotation