Data structure and algorithm 2 Heap trees 1

  • Slides: 8
Download presentation
Data structure and algorithm 2 Heap trees 1

Data structure and algorithm 2 Heap trees 1

Lecture out lines n n n Defintion of heap Heap types. Max heap. Min

Lecture out lines n n n Defintion of heap Heap types. Max heap. Min heap. Operation on heap.

The Heap Data Structure n n Heap is a special case of balanced binary

The Heap Data Structure n n Heap is a special case of balanced binary tree data structure where the root-node key is compared with its children and arranged accordingly. If x has child node y then − key(x) ≥ key(y) 20 7 5 6 2 Max Heap 3

n Structural property: all levels are full, except possibly the last one, which is

n Structural property: all levels are full, except possibly the last one, which is filled from left to right n Order (heap) property: for any node x Parent(x) ≥ x

Array Representation of Heaps A heap can be stored as an array A. Root

Array Representation of Heaps A heap can be stored as an array A. Root of tree is A[1] Left child of A[i] = A[2 i] Right child of A[i] = A[2 i + 1] Parent of A[i] = A[ i/2 ] Heapsize[A] ≤ length[A] The elements in the subarray A[( n/2 +1). . n] are leaves

Heap Types Max-heaps (largest element at root), have the maxheap property: for all nodes

Heap Types Max-heaps (largest element at root), have the maxheap property: for all nodes i, excluding the root: A[PARENT(i)] ≥ A[i] Min-heaps (smallest element at root), have the minheap property: for all nodes i, excluding the root: A[PARENT(i)] ≤ A[i] 6

Adding/Deleting Nodes n n New nodes are always inserted at the bottom level (left

Adding/Deleting Nodes n n New nodes are always inserted at the bottom level (left to right) Nodes are removed from the bottom level (right to left) 7

Operations on Heaps Maintain/Restore the max-heap property MAX-HEAPIFY Create a max-heap from an unordered

Operations on Heaps Maintain/Restore the max-heap property MAX-HEAPIFY Create a max-heap from an unordered array BUILD-MAX-HEAP Sort an array in place HEAPSORT Priority queues 8