Вы находитесь на странице: 1из 19

H ( complete binary tree) is called a HEAP or maxheap if each node N of H has the following property :

The value of N is greater than or equal to the value at each of children of N. i.e IT MEANS LARGEST ELEMENT in H appears at the top of the HEAP ie. root

TREE[K] has its left child at TREE[2*K] And has its right child at TREE[2*K+1] _____________________________________ A NODE J has its parent at the NODE TREE[J/2]

97

88

95

66

55

95

97

88

95

66

55

95

SEQUENTIAL REPRESENTATION

SUPPOSE H is a HEAP with N elements and suppose an ITEM of information is given.WE insert ITEM into a HEAP H as follows :
1.

FIRST adjoin ITEM at the end of H so that H is still a complete tree, but not necessarily a heap. Then let ITEM rise to its appropriate place in H so that H is finally a heap.

2.

97

88 55

48

97

88 55

48

70

97

88 55

70

48

97

88

70

55

48

PTR GIVES the location of item as it rises in the tree

PAR denotes the location of the parent of ITEM

INSHEAP(TREE,N,ITEM) Set N=N+1 and PTR=N While PTR > 1 Set PAR=Floor[PTR/2] If ITEM <= TREE[PAR] then Set TREE[PTR]=ITEM and Return End of If Set TREE[PTR]=TREE[PAR] Set PTR=PAR End of loop Set TREE[1]=ITEM

CREATE A HEAP OF

44,30,50,22,60,55,77,55

Suppose H is a heap with N elements and suppose we want to delete the root R of H.This is accomplished as follows : 1. Assign the root R to some variable ITEM 2. Replace the deleted node R by the last node L of H so that H is still a complete tree but not necessarily a heap. 3.(Reheap) Let L sink to its appropriate place in H so that H is finally a heap

LAST saves the value of the original last node of H SINKING PTRGIVES LOCATION Of LAST LEFTGIVES LOCATION of left of LAST
RIGHTGives LOCATION of right of LAST

DELHEAP(TREE,N,ITEM)
Set ITEM=TREE[1] Set LAST=TREE[N] and N=N-1 Set PTR=1 LEFT=2 and RIGHT=3 While RIGHT <=N

If LAST>=TREE[LEFT] and LAST >=TREE[RIGHT] then


Set TREE[PTR]=LAST and Return

If TREE[RIGHT]<=TREE[LEFT] then
Set TREE[PTR]=TREE[LEFT] and PTR=LEFT Else Set TREE[PTR]=TREE[RIGHT] and PTR=RIGHT End of If Set LEFT=2*PTR and RIGHT=LEFT+1 End of loop If LEFT=N and if LAST < TREE[LEFT] then Set PTR=LEFT Set TREE[PTR]=LAST Return

95

85

70

55

33

30

65

15 15 20

22

DELETE

ROOT

22

85

70

55

33

30

65

15 15 20

DELETE

ROOT

85

22

70

55

33

30

65

15 15 20

DELETE

ROOT

85

55

70

22

33

30

65

15 15 20

DELETE

ROOT

Вам также может понравиться