0% found this document useful (0 votes)
11 views

UNIT 4.1 (Tree, BST, HeapTree, Heapsort)

Uploaded by

kushalreddy272
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

UNIT 4.1 (Tree, BST, HeapTree, Heapsort)

Uploaded by

kushalreddy272
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 118

Unit-IV

Topics to be covered
Trees: Definitions and Concepts
properties of Binary Trees
types of binary trees
Representation of binary tree
 Tree Traversal.
 Binary Search Trees: Representation and operations.
 Tries- Definition and uses
Heap Tree: Definition
Heap Tree Representation
 Heap Sort.
 Balanced Search Trees: AVL Trees

S. Dura Devi ,CSE,CBIT


S. Dura Devi, CSE,CBIT
General View of a Tree

leaves

nodes

branches

root

S. Durga Devi , CSE, CBIT


Computer Scientist’s View

root
leaves

branches

nodes

S. Durga Devi , CSE, CBIT


Trees
Definition:- Tree is a non linear data structures. It is a collection of
entities called nodes.
A tree is a finite set of one or more nodes such that:
i) There is a specially designated node called the root.
ii) Remaining nodes are partitioned into ‘n’ (n>0) disjoint sets
T1,T2,..Tn, where each Ti (i=1,2,….n) is a Tree, T1,T2,..Tn are
structure of a tree called sub tree of the root.

T1 A T3
T2
B C D

E F G H I J

K L
S. Durga Devi , CSE, CBIT
A tree satisfies the following properties:

1. It has one designated node, called the root, that has no parent.
2. Every node, except the root, has exactly one parent.
3. A node may have zero or more children.
4. There is a unique directed path from the root to each node.

5 5
5
1
3 2 3 2
3 2

4 1 6 4 6
4 1 6
tree Not a tree Not a tree

S. Durga Devi , CSE, CBIT


Tree Terminology
Root: node without parent (A)
Internal node: node with at least one child
(A, B, C, F)
External node (leaf ): node without
children (E, I, J, K, G, H, D)
Ancestors of a node: parent, grandparent,
grand-grandparent, etc. A
Descendant of a node: child, grandchild,
grand-grandchild, etc.
Level : set of nodes with same depth called
depth and root is termed as in level 0. If a B C D
node is at level i and its child is at level i+1
and parent is at level i-1. This is true for all
except the root node.
Depth of a node: number of ancestors
E F G H
Height of a tree: maximum depth of any
node (3)
Degree of a node: the number of its children
Degree of a tree: the maximum number of
its node. I J K subtree
Subtree: tree consisting of a node and its
descendants.
Sibling: node have same parent . I,J,K has
parent F.

S. Durga Devi , CSE, CBIT


• Path: a sequence of nodes and edges
connecting a node with descendants.

S. Durga Devi , CSE, CBIT


• Height of a tree:
• The height of tree is no of edges present in longest path of a tree
• Height of a node is the number of edges on the longest path from the node
to a leaf.

Height of a tree is 3 that is from
A->C->D->E
Not from A to G

S. Durga Devi , CSE, CBIT


• The depth of a node is the number of edges from root node to that particular node.
A root node will have a depth of 0.t

Note: depth and height of the tree


returns same value. But for individual
nodes gives different values.

S. Durga Devi , CSE, CBIT


- size:- size of a node is number of descendants and node itself. Node F size is 4.
- Skew trees: every node is a tree has exactly one child except the leaf node is called
skew tree.
- if every node has only left child is called left skew tree
- if every node has only right child is called right skew tree.

S. Durga Devi , CSE, CBIT


Applications of Trees
Trees are most useful data structures in computer science. Some of the
applications of trees are
1. Library database in library, students database in schools and colleges,
patients database in hospitals, employee database in an organization or any
database implemented using trees.
2. The file system in your computer i.e folders and all files, would be stored
as a tree
3. When you search for a word or misspelled you would get list of possible
corrected words, you are using tree.
4. When you watch you tube video’s or surfing internet you would get all the
information in your computer which is somewhere in the world would
travel to your computer through many intermediate computers called
routers. Routers uses tree for routing data.

S. Durga Devi , CSE, CBIT


Tree ADT

integer size()  boolean isInternal(p)


boolean isEmpty() -boolean isExternal(p)
objectIterator elements() -boolean isRoot(p)
positionIterator positions()
-swapElements(p, q)
position root()
-object replaceElement(p, o)
position parent(p)
positionIterator Additional update methods may be
children(p) defined by data structures
implementing the Tree ADT
Types of trees
1. Binary tree
2. Binary search tree
3. Heap tree
4. Balanced binary trees
4.1. AVL- trees
4.2.Red-Black trees
4.3.Splay trees
4.4.B- Trees
S. Durga Devi , CSE, CBIT
Binary Trees
• Definition :-
A binary tree is a finite set of nodes such that
i. T is empty tree (called empty binary tree)
ii. T contains a specially designed node called the root of T, and remaining
nodes of T form two disjoint binary trees T1 and T2 which are called left
sub tree and right sub tree respectively.
iii. Each node in binary tree has at most two children. (0,1,2)

Example of binary tree Left Right sub tree


A
sub tree
root B C

D E F G
left Right
sub sub H I J
tree tree
K S. Durga Devi , CSE, CBIT
• Difference between tree and binary tree
Trees
1.Tree never be empty Binary tree
2. A node may have any no of 1. May be empty
children nodes. 2. A node may have
at most two children
0, 1, or 2
Three special situations of a binary tree are possible
1.Full binary tree
2.Complete binary tree.
3. Strict binary tree

S. Durga Devi , CSE, CBIT


Full binary tree
A binary tree is a full binary tree, if it contains maximum
possible number of nodes in all levels.

1 Level 0- 1node
2 3 Level 1-2nodes
4 5 6 7
Level 2-4 nodes
8 9 10 11 12 13 14 15 Level 3-8nodes
Complete binary tree
A binary tree is said to be complete binary tree, if all its levels have maximum
number of nodes except possibly the last level, and In the last level, the nodes
are attached starting from the left-most position. All leaf nodes at height h or h-
1.
1 A
Level 0-1node
2 3 Level 1-2 nodes
B C Not a CBT
4 5 6 7 Level 2- 4 nodes D E F G
8 9 Level 3- 2 nodes H I J
K Devi
S. Durga Not, CSE,
a CBTCBIT
3. strict binary tree:
every node in binary tree has exactly two
children except the leaf nodes.

B C

D E F G

H I

S. Durga Devi , CSE, CBIT


Applications of trees
 Trees used to develop compilers.
Huffman code trees used in data compression
algorithms.
B- trees used in data bases.

S. Durga Devi , CSE, CBIT


Binary tree representation
1. linear\sequential representation
2. Linked list

1. linear\sequential representation (using arrays)

 The nodes are stored level by level, starting from the zero level
where root node is present.
the following rules can be used to decide the location of any node of a
tree in the array.
a. The root node is at location 0.
b. If a node is at a location ‘i’, then its left child is located at 2 * i + 1
and right child is located at 2 * i + 2
c. The space required by an n node binary tree is 2n+1.

S. Durga Devi , CSE, CBIT


Example- linear\sequential representation
1
A

2 3
B D

4 6 7
C E G

13
F

A B D C . E G . . . . . F

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Sequential representation

S. Durga Devi , CSE, CBIT


Advantages of linear representation
1. Any node can be accessed from any other node by calculating the index
and this is efficient from execution point of view.
2. There is no overhead of maintaining the pointers.
3. Some programming languages like BASIC, FORTRAN, where dynamic
allocation is not possible, array representation is the only way to store a
tree.

disadvantages

1. Other than full binary tree, if u store any type of tree most of the memory
locations are empty.
2. Allows only static representation. There is no possible way to enhance
the size of the tree.
3. Inserting a new node and deleting a node from it are inefficient with
this representation because these require considerable data movement up
and down the array which demand excessive processing time.

S. Durga Devi , CSE, CBIT


Representation of Binary Tree using Linked List

 The most popular way to present a binary tree.


 Each element is represented by a node that has two link fields (leftChild
and rightChild) plus an element field .
 The space required by an n node binary tree is n * sizeof a node.

struct node { /* a node in the tree structure */


struct node *lchild;
int data ;
struct node *rchild;
};
The pointer lchild stores the address of left child node.
The pointer rchild stores the address of right child node.
If child is not available NULL is stored.
A pointer variable root represents the root of the tree.

S. Durga Devi , CSE, CBIT


500
200 +

300 400 100

- 600 * 700

200 500

A B C D

600 700
300 400

S. Durga Devi , CSE, CBIT


python
Structure of a node of a tree
class createnode:
def __init__(self,key):
self.key=key
self.left=None
self.right=None

S. Durga Devi , CSE, CBIT


Binary tree insertion
1. Define structure for a node
• struct node
• {
• int data;
• struct node *left;
• struct node *right;
• };
2. Create new node
• struct node* createNode(int data)
• {
• // Allocate memory for new node
• struct node* node = (struct node*)malloc(sizeof(struct node));

• // Assign data to this node
• node->data = data;

• // Initialize left and right children as NULL
• node->left = NULL;
• node->right = NULL;
• return(node);
• }

S. Durga Devi , CSE, CBIT


int main()
{
// insert new node into a binary tree
struct node * root=createNode(20);
root->lchild=createNode(30); 20

root->rchild=createNode(40);
root->lchild->lchild=createNode(50);
root->rchild->lchild=creatNode(60); 30 40

return 0;
} 50 60

S. Durga Devi , CSE, CBIT


Tree traversals
void preorder(struct node *root)
{ 20
if(root)
{
printf(“%d “,root->data); 30 40
preorder(root->lchild);
preorder(root->rchild);
} 50 60
}
20 30 50 40 60
S. Durga Devi , CSE, CBIT
20

30 40

50 60

S. Durga Devi , CSE, CBIT


Inorder traversal
void inorder(struct node* root)
{
if(root) 20
{
inorder(root->lchild);
printf(“%d “,root->data);
inorder(root->rchild); 30 40
}
}
50
50 60

S. Durga Devi , CSE, CBIT


Post order traversal
void postorder(struct node *root)
{
if(root)
{
postorder(root->lchild);
postorder(root->rchild);
printf(“%d “, root->data);
}
}

S. Durga Devi , CSE, CBIT


write a python program to implement insertion and traversal operations on binary tree

S. Durga Devi , CSE, CBIT


Conversion of general tree to binary tree

• Steps
.
1. Root node of the general tree will become
root node to Binary tree
2. Left most child in general tree will become left
child in binary tree
3. Left node siblings in general tree will become
right child nodes for the left node in binary tree

S. Durga Devi , CSE, CBIT


root
A

General Tree D
E

F G

S. Durga Devi , CSE, CBIT


Properties of binary trees
1. In BT, the maximum number of nodes at level i, where i>=0
at level 0=20=1 node i
at level 1= 21=2 nodes
n= 2
2. The maximum no of nodes possible in a binary tree of height h is
Nmax=2h+1-1 If height=2 maximum no of nodes are 7

3. The minimum no of nodes possible in a binary tree of height h is

Nmin=h+1 If height =3 minimum no of nodes are 3


4. The minimum no of nodes possible at every level is only one node.
When every parent node has on child such kind of tree is called skew
binary tree.

Fig-b S. Durga Devi ,CSE,CBIT


Fig-a
5. for any non empty binary tree, if n is the number of nodes and
e is the number of edges, then n= e+1

6. for any non empty binary tree T, if n0 is the no. of leaf nodes and n2 is
the no. of internal nodes (degree-2), then

n0= n2+1

No of internal nodes n2 =3
No of leaf nodes n0 = 3+1=4
7. Minimum height of a binary tree with n number of nodes is
log2(n+1)
8. Total no of binary trees possible with n nodes is

(1/(n+1) )*2nCn
S. Durga Devi ,CSE,CBIT
• Total no of binary tree possible with 3 nodes is- 5- A,B,C

A A A A
A

B B B B
B C

C C C
1 C
2 3 5
4
Representation of binary tree
1. linear\sequential representation (using arrays).
2. linked representation (using linked list)

S. Durga Devi ,CSE,CBIT


Binary Tree traversals

• This operation is used to visit each node in the tree exactly once.
• The tree can be traversed in various ways.
for a systematic traversal, it is better to visit each node and its sub trees in the
same fashion.
• Following are tree traversals
1. root, left, right- pre order
2. Left, root, right- In order
3. Left, right, root- post order
4. Level by level- level order

S. Durga Devi ,CSE,CBIT


Pre order traversal
1. Visit the root node.
2. Traverse the left sub- tree of root in preorder.
3. Traverse the right sub- tree of root in preorder.
In order traversal
1. Traverse the left sub tree of the root node in in order.
2. visit the root node.
3.Traverse the right sub tree of the root node in in order.

Post order traversal


1.Traverse the left sub tree of the root node in post order.
2. Traverse the right sub tree of the root node in the post order.
3.Visit the root node.

Level order traversal


- visit the root first, then the roots left child, followed by roots right
child.
- we continue in this manner, visiting the nodes at each new level
from the leftmost node to the right most node.
S. Durga Devi ,CSE,CBIT
S. Durga Devi ,CSE,CBIT
S. Durga Devi ,CSE,CBIT
S. Durga Devi ,CSE,CBIT
pre order of binary tree
Pre order- A,B,D,E,H,I,C,F,J,K,G

B C

D E F G

H I J
K S. Durga Devi ,CSE,CBIT
In order of binary tree

A Inorder- D,B,H,E,I,A,F,K,J,C,G

B C

D E F G

J
H I

K
S. Durga Devi ,CSE,CBIT
In order of binary tree

A Inorder- D,B,H,E,I,A,F,K,J,C,G

B C

D E F G

H J
I

K
S. Durga Devi ,CSE,CBIT
Post order of binary tree

A Post order- D,H,I,E,B,K,J,F,G,C,A

B C

D E F G

J
H I

K
S. Durga Devi ,CSE,CBIT
Level order of binary tree

A Level order- A,B,C,D,E,F,G,H,I,J,K

B C

D E F G

J
H I

K
S. Durga Devi ,CSE,CBIT
Write pre,in and post order of the following tree
• (A-B) + C* (D/E)

- *

A B C /

D E

S. Durga Devi ,CSE,CBIT


Pre order for the following tree

+
Pre order- +,-,A,B,*,C,/,D,E.
- *

A B C /

D E

S. Durga Devi ,CSE,CBIT


in order of the following tree

+
Pre order- +,-,A,B,*,C,/,D,E.
- *

A B C /

In order- A,-,B,+,C,*,D,/,E D E
post order of the following tree

+
Pre order- +,-,A,B,*,C,/,D,E.
- *

A B C /

In order- A,-,B,+,C,*,D,/,E D E

Post order- A,B,-,C,D,E,/,*,+


Binary search tree

 Binary search tree is one type of binary tree.


 Binary search tree is a binary tree that may be empty .
 Non empty binary search tree satisfies the following properties.
1. every node has a value and no two elements (node) have same value,
therefore all values are different.
2. The values in the left sub tree are smaller than value of its root node.
3. The values in the right sub tree are greater than its value of the root node.
4. The left and right sub tree of the root also binary search tree.

All<K All>K

S. Durga Devi , CSE, CBIT


• The following are the bst( binary search trees)

35
18
45
15 20

12 17 25 40 50

20
15 25 Its not a binary search
tree because it fails to satisfy
12 the property of 3 and 4
18 22

S. Durga Devi , CSE, CBIT


Binary search tree representation

• Binary search tree representation is same as


binary tree representation
• Refer binary tree representation.

S. Durga Devi ,CSE,CBIT


BST operations
1.create
2. insertion
3. deletion
4.findmax
5.findmin
6.search
7.display

S. Durga Devi ,CSE,CBIT


1. Search operation on BST
• Searching-
suppose we wish to search an element with key or value (K), we begin at the
root. If root is NULL, the search tree contains no such element, the search
is unsuccessful.
• Otherwise, we compare key value with value of root node. if K < key
value in the root, then no element in the right sub tree and only left sub tree
is to be searched.
• If K is greater than key in the root, only the right sub tree is to be searched.
• This process repeated until the key element is found or reached to the leaf
nodes.
• If K= key value in the root, then search terminates successfully. The sub
tree may be searched similarly.

S. Durga Devi ,CSE,CBIT


Example- find a given key node in a following BST

22>20

20
Search node-22
15
25

12
18 22

S. Durga Devi ,CSE,CBIT


Insertion operation on BST
• Insertion operation on a binary search tree is very simple. In fact, one step
more than the searching operation.
• To insert a node with data, say ITEM, into a tree, the tree is to be searched
starting from the root node.
• If ITEM is found, do nothing, otherwise ITEM is to be inserted at the dead
end where search halts.
6 6
Insert node- 5 2 8 2 8

1 4 1 4
3
3 5
a) Before insertion b) After inserting node 5

S. Durga Devi , CSE, CBIT


Construct BST with following elements
19, 55,44,98,8,23,15,6,10,82,99

Root
19

8 55

6 15
44 98

10
23
82 99

S. Durga Devi ,CSE,CBIT


Deletion operation on BST

• Another frequently used operation on the BST is to delete any node from it.
This is slightly complicated one.
• To delete a node from a binary search tree, there are three possible cases
when we delete a node.
case-1- if deleted node is a leaf node or node has no children, it can be deleted
by making its parent pointers ( left, right) to NULL.

30
30

25 40
25 40

20 20 45
35 45

Deleted node-35 b. After deletion


a. Before deletion
S. Durga Devi ,CSE,CBIT
Case-2 if the deleted node has one child, either left child or
right child, its parent pointer needs to be changed.
8
8
Deleted After deletion
6 9 6 9
node-1

1 7
4 7
4

S. Durga Devi ,CSE,CBIT


S. Durga Devi ,CSE,CBIT
S. Durga Devi ,CSE,CBIT
case-3
• If deleted node has two children
• First find out the inorder successor (X) of the deleted node ( in order
successor means the node which comes after the deleted node during the
inorder traversal).
• Delete a node X from tree by using case 1 or case 2 (it can be verified that
x never has a left child) and then replace the data content in deleted node
by the data of the x.
35
35

45 24 45
20

16 42 16 29 42
29

24 27 33
33
x
27
S. Durga Devi
,CSE,CBIT
Merge or join BST
• Another interesting operations on BST are
recombine them (merge) and split BST in
interesting ways.
• Merge: Combine two Binary search trees into
single binary search tree.
• Split: break binary search tree into two binary
search trees.

S. Durga Devi ,CSE,CBIT


• Write a program to implement BST with
following operations
i insertion ii deletion iii inorder iv postorder v
preorder.

S. Durga Devi ,CSE,CBIT


Using Python

S. Durga Devi ,CSE,CBIT


# define a class for the node

#inserting node in BST

S. Durga Devi ,CSE,CBIT


S. Durga Devi ,CSE,CBIT
S. Durga Devi ,CSE,CBIT
Height of binary tree

Height of a tree= no of nodes covered in


Longest path from Root node to leaf node.

S. Durga Devi ,CSE,CBIT


S. Durga Devi ,CSE,CBIT
Height of a Binary Tree
- Get height of the left sub tree say it hl
- Get height of the right sub tree say it hr.
- Take the Maxheight(leftHeight, rightHeight) and add 1 for the root and
return.
- Call recursively.
int Findheight(root)
{
if (root==NULL)
return -1
Leftheight = Findheight(root->left);
Rightheight= Findheight(root->right);
Return max(Leftheight, Rightheight)+1;
}

S. Durga Devi ,CSE,CBIT


Copying a binary tree
• In postorder, the root is visited last
• Here’s a postorder traversal to make a complete copy of a
given binary tree:

• node *copy( root ) :


• if (root == NULL ) : return -1;
• //create new node and make it a copy of node pointed by root
• node *temp = (node *)malloc(sizeof(node)) ;
• temp->data = root-> data; //copying data
• temp->left = copy(root -> left); //cloning left child
• temp->right = copy(root -> right); //cloning right child
• return temp;

S. Durga Devi ,CSE,CBIT


Advantages of linked representation

 This representation is superior to the array representation as there is no


wastage of memory.

 There is no need to have prior knowledge of depth of the tree. Using dynamic
memory allocation concept one can create as much memory (node) as
required.

 Insertion and deletion which are the most common operations can be done
without moving the other nodes.

Disadvantages of linked representation


 This representation does not provide direct access to a node.

 It needs additional space in each node for storing the left and right subtrees.

S. Durga Devi ,CSE,CBIT


Priority queue ADT
• Priority queue is abstract data type which is like a queue or stack data
structure but each element has been assigned a value called priority of the
element, and an element can be inserted or deleted not only at the ends but
at any position in the queue.
• Some contexts where some things should be allowed to skip ahead in the
line?

• Applications
- Lower berths of a train during reservation are allocated first to the old age
persons. Here priority is age of a person.
- In operating system runnable processes might be stored in priority queue,
where certain system processes are given a higher priority than user
processes.
- In networks packets of data routed according to some assigned priorities.

S. Durga Devi ,CSE,CBIT


Priority Queues
• Priority queue means its not FIFO Strictly.
• Elements has priority and insertion and deletion
performed based on the priority.
• Elements are inserted with priority and when you delete
highest priority elements should be deleted first.
• Priority queues are implemented using heap trees.
• If priority queues implemented using heaps time
complexity is O(logn).
• If priority queues implemented using arrays time
complexity will be O(n).

S. Durga Devi ,CSE,CBIT


Heaps
• Heaps are in form of binary tree structure.
• Definition of binary heap:
- heap tree must be complete binary tree
There are two types of binary heaps
1. Max Heap Tree: Max heap is a tree in which the value in each
node is greater than or equal to its children.
2. Min Heap Tree: Min heap is a tree in which the value in each
node is smaller than or equal to its children.

S. Durga Devi ,CSE,CBIT


Max Heap

Min Heap

S. Durga Devi ,CSE,CBIT


Binary Heaps: Array Implementation

• Heap trees are implemented either in linked list or


array.
• Array representation have more advantages over the
linked list because heap tree is a complete binary tree.
So there is no wastage of memory.
• Elements of heap are stored in an array level by level.

S. Durga Devi ,CSE,CBIT


Binary Heaps: Array Implementation

S. Durga Devi ,CSE,CBIT


Insertion into a heap tree
• Insertion into a heap must maintain both the complete binary tree structure
and the heap order property. To do this what we do is the following.
• We know that in order to maintain the complete binary tree structure, we
must add a node to the first open spot at the bottom level. So we begin by
adding a node without data there. After that what we do is we see if
inserting our new value will violate the heap property. If it doesn't put it in
and we are done. Otherwise, we move the value from the parent of the
empty node down , thus creating an empty node where the parent use to
be. We again check to see if inserting the value violates the heap order
property. If not, we add it in. Otherwise repeat the process until we are
able to add the value. This process of moving the empty node towards the
root is called percolate up

S. Durga Devi ,CSE,CBIT


Example
• Construct a min heap with following
elements:10,6,20,5, 16, 17, 13,2

Insert 10
10

S. Durga Devi ,CSE,CBIT


Insert 6
10

6
6<10 swap with parent 10

S. Durga Devi ,CSE,CBIT


Insert 6
6

10

S. Durga Devi ,CSE,CBIT


Insert 20
6

10 20

20>6 need not swap

S. Durga Devi
,CSE,CBIT
Insert 5
6

10 20

5< 10 then swap


5

S. Durga Devi ,CSE,CBIT


Insert 5
6

5 20

5< 6 then swap


10

S. Durga Devi ,CSE,CBIT


Insert 5 5

6 20

5< 6 then swap


10

S. Durga Devi ,CSE,CBIT


Insert 16 5

6 20

16>6 need not swap


10
16

S. Durga Devi ,CSE,CBIT


Insert 16 5

6 20

16>6 need not swap


10
16

S. Durga Devi ,CSE,CBIT


5
Insert 17

6 20

17<20 then swap


10 17
16

S. Durga Devi ,CSE,CBIT


5
Insert 17

6 17

17<20 then swap


10 20
16

S. Durga Devi ,CSE,CBIT


Insert 13 5

6 17

13<17 then swap


10 20
16 13

S. Durga Devi ,CSE,CBIT


Insert 13 5

6 13

13<17 then swap


10
16 20 17

S. Durga Devi ,CSE,CBIT


Insert 2
5

6 13

2<10 then swap


10
16 20 17

S. Durga Devi ,CSE,CBIT


5
Insert 2

6 13

2<6 then swap


2
16 20 17

10

S. Durga Devi ,CSE,CBIT


5
Insert 2

2 13

2<5 then swap


6
16 20 17

10

S. Durga Devi ,CSE,CBIT


Insert 2 2
Time complexity depends on no of swaps.
No of swaps depends on height of binary
tree. O(1) to O(logn)

5 13

2<5 then swap


6
16 20 17

To create a heap time complexity


is O(nlogn).
10
This process of moving the empty node
towards the root is called percolate up

S. Durga Devi ,CSE,CBIT


Heap tree deletion
Deletion process for min heap tree
1. Remove root (that is always the min!)
2. Replace root node with “last” leaf node in the heap
tree.
3. Find smallest child of node
4. Swap node with its smallest child if needed.
5. Repeat steps 3 & 4 until no swaps needed.
6. Tree must satisfy the properties of heap tree.

This process of moving the empty node towards the child is called percolate
down

S. Durga Devi ,CSE,CBIT


DeleteMin

2 20

4 5 4 5

7 6 10 8 7 6 10 8

11 9 12 14 20 11 9 12 14 20

S. Durga Devi ,CSE,CBIT


Percolate Down
20 4

4 5 20 5

7 6 10 8 7 6 10 8

11 9 12 14 11 9 12 14

4 4

6 5 6 5

7 20 10 8 7 12 10 8

11 9 12 14 11 9 20 14
S. Durga Devi ,CSE,CBIT
Heap sort
• There are two main applications of heap tree
1. sorting data ( heap sort)
2. implement priority queue.
Heap sort:
to sort the data in ascending(Descending)
order, build max heap (min heap) .

S. Durga Devi ,CSE,CBIT


Heap sort

S. Durga Devi ,CSE,CBIT


Why Heapsort?
• It is a well-known, traditional sorting
algorithm you will be expected to know
• Heapsort is always O(n log n)
– Quicksort is usually O(n log n) but in the worst
case slow down to O(n2)
– Quicksort is generally faster, but Heapsort is better
in time-critical applications
• Heapsort is a really cool algorithm!

S. Durga Devi ,CSE,CBIT


Heap sort
• Algorithm
1. Build a tree with the given data
2. a) delete root node from the heap
b) rebuild the heap tree after the deletion.
c) place the deleted node in the output array.
3. Continue step 2 until the heap tree is empty.
Note: To sort the data in ascending( descending)
construct max(min) heap in the step 1

S. Durga Devi ,CSE,CBIT


Mapping into an array
25

23 17

19 22 14 15

18 14 21 3 9 11
0 1 2 3 4 5 6 7 8 9 10 11 12
25 23 17 19 22 14 15 18 14 21 3 9 11

• Notice:
– The left child of index i is at index 2*i+1
– The right child of index i is at index 2*i+2
– Example: the children of node 3 (19) are 7 (18) and 8 (14)
S. Durga Devi ,CSE,CBIT
25

23 17

19 22 14 15

18 14 21 3 9 11

S. Durga Devi ,CSE,CBIT


11

23 17

19 22 14 15

18 14 21 3 9 25

S. Durga Devi ,CSE,CBIT


23

11 17

19 22 14 15

18 14 21 3 9 25

S. Durga Devi ,CSE,CBIT


23

22 17

19 11 14 15

18 14 21 3 9 25

S. Durga Devi ,CSE,CBIT


23

22 17

19 21 14 15

18 14 11 3 9 25

0 1 2 3 4 5 6 7 8 9 10 11 12
23 22 17 19 21 14 15 18 14 11 3 9 25

S. Durga Devi ,CSE,CBIT


23

22 17

19 21 14 15

18 14 11 3 9

S. Durga Devi ,CSE,CBIT


9

22 17

19 21 14 15

18 14 11 3 23

S. Durga Devi ,CSE,CBIT


22

9 17

19 21 14 15

18 14 11 3 23

S. Durga Devi ,CSE,CBIT


22

21 17

19 9 14 15

18 14 11 3 23

S. Durga Devi ,CSE,CBIT


22

21 17

19 11 14 15

18 14 9 3

Continue this process until tree is empty

S. Durga Devi ,CSE,CBIT


• Build a heap tree with following elements and
sort them in ascending order using heap sort
• 25,57,48,38,10,91,84,33

S. Durga Devi ,CSE,CBIT

You might also like