1 Heap and Others 黃兆武. 2 Heap A max tree is a tree in which the key value in each node is no smaller than the key values in its children. A max heap is.

Slides:



Advertisements
Similar presentations
AVL Trees1 Part-F2 AVL Trees v z. AVL Trees2 AVL Tree Definition (§ 9.2) AVL trees are balanced. An AVL Tree is a binary search tree such that.
Advertisements

Trees Types and Operations
S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
C. Y. Tang and J. S. Roger Jang
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
©Brooks/Cole, 2003 Chapter 12 Abstract Data Type.
CHAPTER 5 PRIORITY QUEUES (HEAPS) §1 ADT Model Objects: A finite ordered list with zero or more elements. Operations:  PriorityQueue Initialize( int.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
Binary Trees Terminology A graph G = is a collection of nodes and edges. An edge (v 1,v 2 ) is a pair of vertices that are directly connected. A path,
CHAPTER 51 CHAPTER 5 CHAPTER 5 Trees All the programs in this file are selected from Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed “Fundamentals.
Review of Chapter 5 張啟中. Threaded Binary Tree 利用 Binary Tree 節點中的 0-links ,指向中序的先行 者或後繼者,以方便中序追蹤。 Threading Rules  A 0 RightChild field at node p is.
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
Heaps & Priority Queues Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
CS Data Structures Chapter 5 Trees. Additional Binary Tree Operations (1/7)  Copying Binary Trees  we can modify the postorder traversal algorithm.
Department of Computer Eng. & IT Amirkabir University of Technology (Tehran Polytechnic) Data Structures Lecturer: Abbas Sarraf Trees.
CSC2100B Tutorial 7 Heap Jianye Hao.
Chapter 5 Trees: Outline
Bioinformatics Programming 1 EE, NCKU Tien-Hao Chang (Darby Chang)
§3 Binary Heap 1. Structure Property: 【 Definition 】 A binary tree with n nodes and height h is complete iff its nodes correspond to the nodes numbered.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Min Chen School of Computer Science and Engineering Seoul National University Data Structure: Chapter 7.
Been-Chian Chien,Wei-Pang Yang and Wen-Yang Lin 5-1 Chapter 5 Trees Introduction to Data Structures CHAPTER 5 Trees 5.1 Introduction 5.2 Binary Trees 5.3.
CS Data Structures Chapter 5 Trees. Chapter 5 Trees: Outline  Introduction  Representation Of Trees  Binary Trees  Binary Tree Traversals 
1 CSE 1342 Programming Concepts Trees. 2 Basic Terminology Trees are made up of nodes and edges. A tree has a single node known as a root. –The root is.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
For Monday Read Weiss, chapter 7, sections 1-3. Homework –Weiss, chapter 4, exercise 6. Make sure you include parentheses where appropriate.
Tree Data Structures.
CHAPTER 51 CHAPTER 5 CHAPTER 5 Trees All the programs in this file are selected from Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed “Fundamentals.
Binary Trees Definition A binary tree is: (i) empty, or (ii) a node whose left and right children are binary trees typedef struct Node Node; struct Node.
Starting at Binary Trees
Lec 15 Oct 18 Binary Search Trees (Chapter 5 of text)
Preview  Graph  Tree Binary Tree Binary Search Tree Binary Search Tree Property Binary Search Tree functions  In-order walk  Pre-order walk  Post-order.
CHAPTER 5 PRIORITY QUEUES (HEAPS) §1 ADT Model Objects: A finite ordered list with zero or more elements. Operations:  PriorityQueue Initialize( int.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
Heaps & Priority Queues
Binary Search Trees (BST)
Trees. 2 Root leaf CHAPTER 5 3 Definition of Tree n A tree is a finite set of one or more nodes such that: n There is a specially designated node called.
Contents of Chapter 2 Sections –2.1 Stacks and Queues –2.2 Trees –2.3 Dictionaries –2.4 Priority queues –2.5 Sets and disjoint set union –2.6 Graphs –2.7.
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part R3. Priority Queues.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
§3 Binary Tree Traversals —— visit each node exactly once L ::= move left ; R ::= move right ; V ::= visit the node. We will always traverse the left.
1 CSE 326: Data Structures Trees Lecture 6: Friday, Jan 17, 2003.
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)
 آشنايي با درخت  درخت هاي دودويي  پيمايش درختان  هرم  جنگل اهداف 1.
Non Linear Data Structure
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
Yuanming Yu CSCI2100B Data Structures Tutorial 7
Lecture 22 Binary Search Trees Chapter 10 of textbook
EEE2108: Programming for Engineers Chapter 5. Trees
CSCE 3100 Data Structures and Algorithm Analysis
Bohyung Han CSE, POSTECH
TREE DATA STRUCTURE Data Structure 21-Sep-18 Tree
Trees-1 Data Structures with C Chpater-5 Course code: 10CS35
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
CSCI2100 Data Structures Tutorial 7
CHAPTER 5 Trees All the programs in this file are selected from
Data Structures Chapter 5: Trees.
CSCE 3110 Data Structures and Algorithm Analysis
Binary Trees, Binary Search Trees
CSCE 3110 Data Structures and Algorithm Analysis
CSCE 3110 Data Structures and Algorithm Analysis
Tree.
Heaps By JJ Shepherd.
Priority Queue and Heap
Binary Trees, Binary Search Trees
Presentation transcript:

1 Heap and Others 黃兆武

2 Heap A max tree is a tree in which the key value in each node is no smaller than the key values in its children. A max heap is a complete binary tree that is also a max tree. A min tree is a tree in which the key value in each node is no larger than the key values in its children. A min heap is a complete binary tree that is also a min tree. Operations on heaps –creation of an empty heap –insertion of a new element into the heap; –deletion of the largest element from the heap

3 *Figure 5.25: Sample max heaps (p.219) [4] [1] [2][3] [5] [6] [1] [2] [3] [4] [1] [2] Property: The root of max heap (min heap) contains the largest (smallest).

[1] [2][3] [5] [6] [1] [2] [3] [4] [1] [2] [4] *Figure 5.26:Sample min heaps (p.220)

5 Application: priority queue machine service –amount of time (min heap) –amount of payment (max heap) factory –time tag

6 Example of Insertion to Max Heap initial location of new node insert 21 into heap insert 5 into heap

7 Insertion into a Max Heap void insert_max_heap(element item, int *n) { int i; if (HEAP_FULL(*n)) { fprintf(stderr, “the heap is full.\n”); exit(1); } i = ++(*n); while ((i!=1)&&(item.key>heap[i/2].key)) { heap[i] = heap[i/2]; i /= 2; } heap[i]= item; } 2 k -1=n ==> k=  log 2 (n+1)  O(log 2 n)

8 Example of Deletion from Max Heap 20 remove

9 Deletion from a Max Heap element delete_max_heap(int *n) { int parent, child; element item, temp; if (HEAP_EMPTY(*n)) { fprintf(stderr, “The heap is empty\n”); exit(1); } /* save value of the element with the highest key */ item = heap[1]; /* use last element in heap to adjust heap */ temp = heap[(*n)--]; parent = 1; child = 2;

10 while (child <= *n) { /* find the larger child of the current parent */ if ((child < *n)&& (heap[child].key<heap[child+1].key)) child++; if (temp.key >= heap[child].key) break; /* move to the next lower level */ heap[parent] = heap[child]; child *= 2; } heap[parent] = temp; return item; }

11 26 [1] 5 [2] 77 [3] 1 [4] 61 [5] 11 [6] 59 [7] 15 [8] 48 [9] 19 [10] Heap Sort input file

12 77 [1] 61 [2] 59 [3] 48 [4] 19 [5] 11 [6] 26 [7] 15 [8] 1 [9] 5 [10] initial heap exchange Heap Sort

13 61 [1] 48 [2] 59 [3] 15 [4] 19 [5] 11 [6] 26 [7] 5 [8] 1 [9] 77 [10] 59 [1] 48 [2] 26 [3] 15 [4] 19 [5] 11 [6] 1 [7] 5 [8] 61 [9] 77 [10] (a) (b) Heap Sort

14 48 [1] 19 [2] 26 [3] 15 [4] 5 [5] 11 [6] 1 [7] 59 [8] 61 [9] 77 [10] 26 [1] 19 [2] 11 [3] 15 [4] 5 [5] 1 [6] 48 [7] 59 [8] 61 [9] 77 [10] (c) (d) Heap Sort

15 Heap Sort void adjust(element list[], int root, int n) { int child, rootkey; element temp; temp=list[root]; rootkey=list[root].key; child=2*root; while (child <= n) { if ((child < n) && (list[child].key < list[child+1].key)) child++; if (rootkey > list[child].key) break; else { list[child/2] = list[child]; child *= 2; } list[child/2] = temp; } i 2i 2i+1

16 Heap Sort void heapsort(element list[], int n) { int i, j; element temp; for (i=n/2; i>0; i--) adjust(list, i, n); for (i=n-1; i>0; i--) { SWAP(list[1], list[i+1], temp); adjust(list, 1, i); } ascending order (max heap) n-1 cylces top-down bottom-up

17 AVL 樹 (Balanced Binary Tree) 1.T 是一個非空的二元樹, Tl 及 Tr 分別是它的左右子樹,若符合下列兩條件,則稱T為高度平 衡樹。( Height Balancing Binary Tree) (1) TL 及 TR 也是高度平衡樹 (2) | HL-HR | <= 1 , HL 及 HR 分別為 TL 及 TR 的高度。 X ○

Route balanced tree A binary tree with n nodes, where all nodes are at depth └ lg(n) ┘ or less, and where there are exactly 2 d nodes at depth d for each depth 0 <= d < └ lg(n) ┘, will be called route balanced. Perfectly balanced tree All six are route balanced

19 Threaded Binary Trees Two many null pointers incurrent representation of binary trees n: number of nodes number of non-null links: n-1 total links: 2n null links: 2n-(n-1)=n+1 Replace these null pointers with some useful “threads”.

20 Threaded Binary Trees (Continued) If ptr->left_child is null, replace it with a pointer to the node that would be visited before ptr in an inorder traversal If ptr->right_child is null, replace it with a pointer to the node that would be visited after ptr in an inorder traversal

21 A Threaded Binary Tree ABCGEIDHF root dangling inorder traversal: H, D, I, B, E, A, F, C, G

22 TRUE FALSE Data Structures for Threaded BT typedef struct threaded_tree *threaded_pointer; typedef struct threaded_tree { short int left_thread; threaded_pointer left_child; char data; threaded_pointer right_child; short int right_thread; }; left_thread left_child data right_child right_thread FALSE: child TRUE: thread

23 Memory Representation of A Threaded BT f f -- f f A f f C f f B t t E t t F t t G f f D t t I t t H root

24 Next Node in Threaded BT threaded_pointer insucc(threaded_pointer tree) { threaded_pointer temp; temp = tree->right_child; if (!tree->right_thread) while (!temp->left_thread) temp = temp->left_child; return temp; }

25 Inorder Traversal of Threaded BT void tinorder(threaded_pointer tree) { /* traverse the threaded binary tree inorder */ threaded_pointer temp = tree; for (;;) { temp = insucc(temp); if (temp==tree) break; printf(“%3c”, temp->data); } O(n)

26 Inserting Nodes into Threaded BTs Insert child as the right child of node parent –change parent->right_thread to FALSE –set child->left_thread and child->right_thread to TRUE –set child->left_child to point to parent –set child->right_child to parent->right_child –change parent->right_child to point to child

27 Examples root parent A B C D child root parent A B C D child empty Insert a node D as a right child of B. (1) (2) (3)

28 *Figure 5.24: Insertion of child as a right child of parent in a threaded binary tree (p.217) nonempty (1) (3) (4) (2)

29 Selection Trees (1)winner tree (2)loser tree

30 winner tree run 1 run 2 run 3 run 4 run 5 run 6 run 7 run 8 ordered sequence sequential allocation scheme (complete binary tree) Each node represents the smaller of its two children

31 *Figure 5.35: Selection tree of Figure 5.34 after one record has been output and the tree restructured(nodes that were changed are ticked)    

32 Analysis K: # of runs n: # of records setup time: O(K)(K-1) restructure time: O(log 2 K)  log 2 (K+1)  merge time: O(nlog 2 K) slight modification: tree of loser –consider the parent node only (vs. sibling nodes)

Run overall winner *Figure 5.36: Tree of losers corresponding to Figure 5.34 (p.235)

34 Activity on Vertex (AOV) Network n definition A directed graph in which the vertices represent tasks or activities and the edges represent precedence relations between tasks. n predecessor (successor) vertex i is a predecessor of vertex j iff there is a directed path from i to j. j is a successor of i. n partial order a precedence relation which is both transitive (  i, j, k, i  j & j  k => i  k ) and irreflexive (  x  x  x). n acylic graph a directed graph with no directed cycles

35 *Figure 6.38: An AOV network (p.305) Topological order: linear ordering of vertices of a graph  i, j if i is a predecessor of j, then i precedes j in the linear ordering C1, C2, C4, C5, C3, C6, C8, C7, C10, C13, C12, C14, C15, C11, C9 C4, C5, C2, C1, C6, C3, C8, C15, C7, C9, C10, C11, C13, C12, C14

36 *Program 6.13: Topological sort (p.306) for (i = 0; i <n; i++) { if every vertex has a predecessor { fprintf(stderr, “Network has a cycle. \n “ ); exit(1); } pick a vertex v that has no predecessors; output v; delete v and all edges leading out of v from the network; }

37 *Figure 6.39:Simulation of Program 6.13 on an AOV network (p.306) v0 no predecessor delete v0->v1, v0->v2, v0->v3 v1, v2, v3 no predecessor select v3 delete v3->v4, v3->v5 select v2 delete v2->v4, v2->v5 select v5 select v1 delete v1->v4

38 *Figure 6.40:Adjacency list representation of Figure 6.30(a) (p.309) 0  1  2  3 NULL 1  4 NULL 1  4  5 NULL 1  5  4 NULL 3 NULL 2 NULL V 0 V 1 V 2 V 3 V 4 V 5 v0 v1 v2 v3 v4 v5 count link headnodes vertex link node

39 typedef struct node *node_pointer; typedef struct node { int vertex; node_pointer link; }; typedef struct { int count; node_pointer link; } hdnodes; hdnodes graph[MAX_VERTICES]; Topological sort

40 *Program 6.14: Topological sort (p.308) O(n) void topsort (hdnodes graph [], int n) { int i, j, k, top; node_pointer ptr; /* create a stack of vertices with no predecessors */ top = -1; for (i = 0; i < n; i++) if (!graph[i].count) {no predecessors, stack is linked through graph[i].count = top; count field top = i; } for (i = 0; i < n; i++) if (top == -1) { fprintf(stderr, “\n Network has a cycle. Sort terminated. \n”); exit(1); }

41 O(e) O(e+n) Continued } else { j = top; /* unstack a vertex */ top = graph[top].count; printf(“v%d, “, j); for (ptr = graph [j]. link; ptr ;ptr = ptr ->link ){ /* decrease the count of the successor vertices of j */ k = ptr ->vertex; graph[k].count --; if (!graph[k].count) { /* add vertex k to the stack*/ graph[k].count = top; top = k; } } } }