SlideShare a Scribd company logo
1 of 130
Download to read offline
UNIT-IV(Trees,Graphs)
 Trees: Definitions and Concepts
 Operationson Binary Trees
 Representation of binary tree
 Conversion of General Trees to Binary Trees
 Representationsof Binary Trees
 Tree Traversal.
 Binary Search Trees: Representation and operations.
 Heap Tree: definition, representation
 Heap Sort.
 Graphs: Introduction
 Applicationsof graphs
 Graph representations
 graph traversals
 Minimal SpanningTrees.
S. Durga Devi , CSE, CBIT
Trees
S. Durga Devi , CSE, CBIT
General View of a Tree
root
branches
leaves
S. Durga Devi , CSE, CBIT
Computer Scientist’s View
branches
leaves
root
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
called sub tree of the root.structure of a tree
A
B DC
E F G
K L
H I J
T1
T2
T3
S. Durga Devi , CSE, CBIT
Tree Terminology
Root: node without parent (A)
Siblings: nodes share the same parent
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.
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
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
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.
Subtree: tree consisting of a node and its
descendants.
Sibling: node have same parent . I,J,K has
parent F.
A
B DC
G HE F
I J K subtree
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
• A leaf node will have a height of 0.
• Height of a node is the number of edges on the longest path from the node
to a leaf.
•
S. Durga Devi , CSE, CBIT
Height of node A is 3 that is from
A->C->D->E
Not from A to G
• 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
S. Durga Devi , CSE, CBIT
Note: depth and height of the tree
returns same value. But for individual
nodes gives different values.
- 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
Tree ADT
integer size()
booleanisEmpty()
objectIteratorelements()
positionIteratorpositions()
position root()
position parent(p)
positionIterator
children(p)
 booleanisInternal(p)
-booleanisExternal(p)
-booleanisRoot(p)
-swapElements(p,q)
-object replaceElement(p,o)
Additional updatemethods may be
defined by data structures
implementing the Tree ADT
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
2
4 1 6
3
5
2
4 1 6
3
5
2
4
1
6
3
tree Not a tree Not a tree
Types of trees
1. Binary tree
2. Binary search tree
3. Heap tree
4. AVL- trees
5. Red-Black trees
6. Splay trees
7. 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 containsa specially designed nodecalled 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 nodein binary tree has at most two children. (0,1,2)
Example of binary tree Right sub tree
A
B C
D E
H I
F G
J
K
Left
sub tree
root
Right
sub
tree
left
sub
tree
• Difference between tree and binary tree
Trees
1.Tree never be empty
2. A node may have any no of
children nodes.
Binary tree
1. May be empty
2. A node may have
at most two children
0, 1, or 2
Two 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
2 3
4 5 6 7
8 9 10 11 12 13 14 15
Level 0- 1node
Level 1-2nodes
Level 2-4 nodes
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
2 3
4 5 6 7
8 9
Level 0-1node
Level 1-2 nodes
Level 2- 4 nodes
Level 3- 2 nodes
K
A
B C
D E
H I
F G
J
Not a CBTS. Durga Devi , CSE, CBIT
3. strict binary tree:
every node in binary tree has exactly two
children except the leaf nodes.
S. Durga Devi , CSE, CBIT
A
B C
D E
H I
F G
Applications of trees
 express trees used in compilers
Huffman code trees used in data compression
algorithms.
B- trees used in data bases.
S. Durga Devi , CSE, CBIT
1. linearsequential 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
Binary tree representation
1. linearsequential representation
2. Linked list
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
A B D C . E G . . . . . F
Sequential representation
A
C
DB
F
E G
1
2
4
3
76
13
Example- linearsequential representation
S. Durga Devi , CSE, CBIT
Advantages of linear representation
1. Any nodecan be accessed from any other node by calculatingthe 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 representationis the only way to store a
tree.
disadvantages
1. Other than full binary tree, if u store any tree most of the memory
locationsare empty.
2. Allows only static representation. There is no possibleway to enhance
the size of the tree.
3. Inserting a new node and deletinga nodefrom it are inefficient with
this representation becausethese require considerabledata movement up
and down the array which demand excessive processing time.
S. Durga Devi , CSE, CBIT
struct node { /* a nodein 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 pointervariable root representsthe root of the tree.
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)plusan element field.
 The space required by an n node binary tree is n * sizeof a node.
S. Durga Devi , CSE, CBIT
+
- *
A B DC
200
300 400
500
600 700
100
200 500
300 400
600 700
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);
root->rchild=createNode(40);
root->lchild->lchild=createNode(50);
root->rchild->lchild=creatNode(60);
return 0;
}
S. Durga Devi , CSE, CBIT
6050
4030
20
Tree traversals
void preorder(struct node *root)
{
if(root)
{
printf(“%d “,root->data);
preorder(root->lchild);
preorder(root->rchild);
}
}
S. Durga Devi , CSE, CBIT
6050
4030
20
20 30 50 40 60
S. Durga Devi , CSE, CBIT
6050
4030
20
Inorder traversal
void inorder(struct node*root)
{
if(root)
{
inorder(root->lchild);
printf(“%d “,root->data);
inorder(root->rchild);
}
}
50
S. Durga Devi , CSE, CBIT
6050
4030
20
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
S. Durga Devi , CSE, CBIT
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 binarty tree.
S. Durga Devi , CSE, CBIT
General Tree
A
B
I
H
E
F G
C
D
root
Properties of binary trees
1. In BT, the maximum number of nodes at level i, where i>=0
at level 0=20
=1 node
at level 1= 21=2 nodes
2. The maximum no of nodes possible in a binary tree of height h is
Nmax=2h+1-1
n= 2i
3. The minimum no of node possiblein a binary tree of height h is
Nmin=h+1
If height=2 maximum no of nodes are 7
If height =3 minimum no of nodes are 3
4. The minimum no of nodes possibleat every level is only one node.
When every parent node has on childsuch kind of tree is calledskew
binary tree.
Fig-b S. Durga Devi ,CSE,CBIT
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 nodesn0 = 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
B C
1
A
B
C
2
A
B
C
3
A
B
C
4
A
B
C
5
Representation of binary tree
1. linearsequential representation (using arrays).
2. linked representation (using linked list)
S. Durga Devi ,CSE,CBIT
BinarayTree traversals
• This operationis used to visit each node in the tree exactly once.
• The tree can be traversed in various ways.
for a systematic traversal, it is betterto visit each node and its sub trees in the
same fashion.
• Followingare 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 nodein in order.
2. visit the root node.
3.Traverse the right sub tree of the root nodein in order.
Postorder traversal
1.Traversethe left sub tree of the root nodein post order.
2. Traverse the right sub tree of the root nodein 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 continuein 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
A
B C
D E
H I
F G
J
K
Pre order- A,B,D,E,H,I,C,F,J,K,G
S. Durga Devi ,CSE,CBIT
In order of binary tree
A
B C
D E
H I
F G
J
K
Inorder- D,B,H,E,I,A,F,K,J,C,G
S. Durga Devi ,CSE,CBIT
In order of binary tree
A
B C
D E
H I
F G
J
K
Inorder- D,B,H,E,I,A,F,K,J,C,G
S. Durga Devi ,CSE,CBIT
Post order of binary tree
A
B C
D E
H I
F G
J
K
Post order- D,H,I,E,B,K,J,F,G,C,A
S. Durga Devi ,CSE,CBIT
Level order of binary tree
A
B C
D E
H I
F G
J
K
Level order- A,B,C,D,E,F,G,H,I,J,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
+
- *
A B C /
D E
Pre order- +,-,A,B,*,C,/,D,E.
S. Durga Devi ,CSE,CBIT
in order of the following tree
+
- *
A B C /
D E
Pre order- +,-,A,B,*,C,/,D,E.
In order- A,-,B,+,C,*,D,/,E
post order of the following tree
+
- *
A B C /
D E
Pre order- +,-,A,B,*,C,/,D,E.
In 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 nodehas 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.
k
All<K All>K
S. Durga Devi , CSE, CBIT
• The following are the bst( binary search trees)
18
15 20
12 17 25
35
45
5040
20
15 25
12 18 22
Its not a binary search
tree because it fails to satisfy
the property of 3 and 4
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-
supposewe 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
20
15
25
12
18 22
Search node-22
22>20
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 nodewith 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
2 8
1 4
3
a) Before insertion
Insert node- 5
6
2
1 4
3 5
8
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
19
55
98
99
23
44
82
8
6 15
10
Root
S. Durga Devi ,CSE,CBIT
Deletion operation on BST
• Anotherfrequentlyused operation on the BST is to deleteany node from it.
This is slightly complicated one.
• To delete a node from a binary search tree, there are three possible cases
when we deletea node.
case-1-if deleted nodeis a leaf nodeor node has no children, it can be deleted
by making its parent pointers( left, right) to NULL.
30
25 40
20
35 45
30
25 40
20 45
a. Before deletion
b. After deletionDeleted node-35
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.
4
6
8
9
7
After deletion
8
6
7
9
4
1
Deleted
node-1
S. Durga Devi ,CSE,CBIT
S. Durga Devi ,CSE,CBIT
S. Durga Devi ,CSE,CBIT
case-3
• If deleted nodehas two children
• First find out the inorder successor (X) of the deleted node( in order
successor means the node which comes after the deleted nodeduring 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 replacethe data content in deleted node
by the data of the x.
45
35
27
24
2916
20 45
2916
24
35
42 42
3327
x 33
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
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 additionalspace in each nodefor storing the left and right subtrees.
S. Durga Devi ,CSE,CBIT
Threaded binary tree
• In linked list representation thereare more null links than actual pointers. If
there are n nodes n+1 null links are present and total links are 2n.
• To make use of these null pointersthreaded binary trees are introduced.
Definition
• A binary tree is said to be threadedbinary tree by making all right child
pointersthat would normally be null point to the inorder successor of the node,
and all the left child pointers that would normally be null point to the inorder
predecessorof the node.
Advantages
• Inorder traversal can be donefaster without using stack.
• Makes use of null pointersin binary tree.
• Successor and predecessor can be find easily.
S. Durga Devi ,CSE,CBIT
Threaded binary tree…
Threaded binary tree
Binary tree
S. Durga Devi ,CSE,CBIT
Threaded Binary Tree
• Threads are two types
1. One way threaded binary tree
2. Two way threaded binary tree
1. Threaded Binary Tree One-Way
• Accordingly, in the one way threading of T, a thread will appear
in the right field of a node and will point to the next node in the
in-order traversal of T.
• See the bellow example of one-way in-order threading.
S. Durga Devi ,CSE,CBIT
Threaded Binary Tree:
One-Way
Inorder of below tree is: D,B,F,E,A,G,C,L,J,H,K
S. Durga Devi ,CSE,CBIT
2. Threaded Binary Tree Two-Way
• In the two-way threading of T.
• A thread will also appear in the left field of a node and
will point to the preceding node in the in-order traversal
of tree T.
• Furthermore, the left pointer of the first node and the
right pointer of the last node (in the in-order traversal of
T) will contain the null value when T does not have a
header node.
S. Durga Devi ,CSE,CBIT
Threaded Binary Tree
• Bellow figure show two-way in-order threading.
• Here, right pointer=next node of in-order traversal and
left pointer=previous node of in-order traversal
• Inorder of bellow tree is: D,B,F,E,A,G,C,L,J,H,K
S. Durga Devi ,CSE,CBIT
Threaded Binary Tree
S. Durga Devi ,CSE,CBIT
Memory representation of threaded binary tree
• In memory representation we must be able to distinguish between thread and
normal pointers.
• Node structure represented with two additional boolean fields left thread and
right thread to tree node.
• If tree→leftthread==TRUE, then tree→leftchild contains a thread; otherwise, it
contains false value. Similarly, if tree→rightthread == TRUE,
then tree→rightchild contains a thread. Otherwise it contains a false value.
Lefthtread Left child Data Right child Right
thread
S. Durga Devi ,CSE,CBIT
Example
S. Durga Devi ,CSE,CBIT
Threaded Binary Tree
Two-way Threading with Header node
• Again two-way threading has left pointer of the first
node and right pointer of the last node (in the inorder
traversal of T) will contain the null value when T will
point to the header nodes is called two-way threading
with header node threaded binary tree.
S. Durga Devi ,CSE,CBIT
Threaded Binary Tree
• Bellow figure to explain two-way threading with header node.
S. Durga Devi ,CSE,CBIT
Threaded Binary Tree
• Bellow example of link representation of threading
binary tree.
• In-order traversal of bellow tree: G,F,B,A,D,C,E
S. Durga Devi ,CSE,CBIT
Threaded Binary Tree
S. Durga Devi ,CSE,CBIT
Priority queue ADT
• Priority queueis abstract data type which is like a queue or stack data
structurebut 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 operatingsystem 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
Heaps
• Priority queues are implemented using 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
Min Heap
Max 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
10
Insert 10
S. Durga Devi ,CSE,CBIT
10
Insert 6
6
6<10 swap with parent 10
S. Durga Devi ,CSE,CBIT
6
Insert 6
10
S. Durga Devi ,CSE,CBIT
6
Insert 20
10
20>6 need not swap
20
S. Durga Devi
,CSE,CBIT
6
Insert 5
10
5< 10 then swap
20
5
S. Durga Devi ,CSE,CBIT
6
Insert 5
5
5< 6 then swap
20
10
S. Durga Devi ,CSE,CBIT
5Insert 5
6
5< 6 then swap
20
10
S. Durga Devi ,CSE,CBIT
5Insert 16
6
16>6 need not swap
20
10
16
S. Durga Devi ,CSE,CBIT
5Insert 16
6
16>6 need not swap
20
10
16
S. Durga Devi ,CSE,CBIT
5
Insert 17
6
17<20 then swap
20
10
16 17
S. Durga Devi ,CSE,CBIT
5
Insert 17
6
17<20 then swap
17
10
16 20
S. Durga Devi ,CSE,CBIT
5Insert 13
6
13<17 then swap
17
10
16 20 13
S. Durga Devi ,CSE,CBIT
5Insert 13
6
13<17 then swap
13
10
16 20 17
S. Durga Devi ,CSE,CBIT
5
Insert 2
6
2<10 then swap
13
10
16 20 17
2
S. Durga Devi ,CSE,CBIT
5
Insert 2
6
2<6 then swap
13
2
16 20 17
10
S. Durga Devi ,CSE,CBIT
5
Insert 2
2
2<5 then swap
13
6
16 20 17
10
S. Durga Devi ,CSE,CBIT
2Insert 2
5
2<5 then swap
13
6
16 20 17
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
201412911
81067
54
20
2
201412911
81067
54
2
S. Durga Devi ,CSE,CBIT
Percolate Down
1412911
81067
54
20
1412911
81067
520
4
1412911
810207
56
4
1420911
810127
56
4
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 study 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
19
1418
22
321
14
119
15
25
1723
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
• 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
19
1418
22
321
14
119
15
25
1723
S. Durga Devi ,CSE,CBIT
19
1418
22
321
14
259
15
11
1723
S. Durga Devi ,CSE,CBIT
19
1418
22
321
14
259
15
23
1711
S. Durga Devi ,CSE,CBIT
19
1418
11
321
14
259
15
23
1722
S. Durga Devi ,CSE,CBIT
19
1418
21
311
14
259
15
23
1722
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
S. Durga Devi ,CSE,CBIT
19
1418
21
311
14
9
15
23
1722
S. Durga Devi ,CSE,CBIT
19
1418
21
311
14
23
15
9
1722
S. Durga Devi ,CSE,CBIT
19
1418
21
311
14
23
15
22
179
S. Durga Devi ,CSE,CBIT
19
1418
9
311
14
23
15
22
1721
S. Durga Devi ,CSE,CBIT
19
1418
11
39
14 15
22
1721
Continuethis 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

More Related Content

What's hot

Bsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structureBsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structureRai University
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structureZaid Shabbir
 
Data structure lecture 1
Data structure lecture 1Data structure lecture 1
Data structure lecture 1Kumar
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureRai University
 
Data structures (introduction)
 Data structures (introduction) Data structures (introduction)
Data structures (introduction)Arvind Devaraj
 
Data Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer ScienceData Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer ScienceTransweb Global Inc
 
data structure
data structuredata structure
data structurehashim102
 
Data Structures Notes 2021
Data Structures Notes 2021Data Structures Notes 2021
Data Structures Notes 2021Sreedhar Chowdam
 
DATA STRUCTURE
DATA STRUCTUREDATA STRUCTURE
DATA STRUCTURERohit Rai
 
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMARIntroduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMARBHARATH KUMAR
 
Data structure &amp; algorithms introduction
Data structure &amp; algorithms introductionData structure &amp; algorithms introduction
Data structure &amp; algorithms introductionSugandh Wafai
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structurekalyanineve
 
Lecture 1 an introduction to data structure
Lecture 1   an introduction to data structureLecture 1   an introduction to data structure
Lecture 1 an introduction to data structureDharmendra Prasad
 
Ii pu cs practical viva voce questions
Ii pu cs  practical viva voce questionsIi pu cs  practical viva voce questions
Ii pu cs practical viva voce questionsProf. Dr. K. Adisesha
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil duttAnil Dutt
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureRai University
 

What's hot (20)

Data structures using c
Data structures using cData structures using c
Data structures using c
 
Bsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structureBsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structure
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structure
 
Data structure lecture 1
Data structure lecture 1Data structure lecture 1
Data structure lecture 1
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structure
 
Data structures (introduction)
 Data structures (introduction) Data structures (introduction)
Data structures (introduction)
 
Data Structures
Data StructuresData Structures
Data Structures
 
Data Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer ScienceData Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer Science
 
data structure
data structuredata structure
data structure
 
Data Structures Notes 2021
Data Structures Notes 2021Data Structures Notes 2021
Data Structures Notes 2021
 
DATA STRUCTURE
DATA STRUCTUREDATA STRUCTURE
DATA STRUCTURE
 
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMARIntroduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
 
Data structure &amp; algorithms introduction
Data structure &amp; algorithms introductionData structure &amp; algorithms introduction
Data structure &amp; algorithms introduction
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structure
 
Lecture 1 an introduction to data structure
Lecture 1   an introduction to data structureLecture 1   an introduction to data structure
Lecture 1 an introduction to data structure
 
Ii pu cs practical viva voce questions
Ii pu cs  practical viva voce questionsIi pu cs  practical viva voce questions
Ii pu cs practical viva voce questions
 
Data structures using C
Data structures using CData structures using C
Data structures using C
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil dutt
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structure
 
Data Structure Basics
Data Structure BasicsData Structure Basics
Data Structure Basics
 

Similar to Unit 4.1 (tree)

Similar to Unit 4.1 (tree) (20)

Unit iii(dsc++)
Unit iii(dsc++)Unit iii(dsc++)
Unit iii(dsc++)
 
Unit 3.ppt
Unit 3.pptUnit 3.ppt
Unit 3.ppt
 
Lecture 21_Trees - I.pptx
Lecture 21_Trees - I.pptxLecture 21_Trees - I.pptx
Lecture 21_Trees - I.pptx
 
Trees - Data structures in C/Java
Trees - Data structures in C/JavaTrees - Data structures in C/Java
Trees - Data structures in C/Java
 
Dsc++ unit 3 notes
Dsc++ unit 3 notesDsc++ unit 3 notes
Dsc++ unit 3 notes
 
Unit 6 tree
Unit   6 treeUnit   6 tree
Unit 6 tree
 
DSA IV Unit.pptx
DSA IV Unit.pptxDSA IV Unit.pptx
DSA IV Unit.pptx
 
Tree Introduction.pptx
Tree Introduction.pptxTree Introduction.pptx
Tree Introduction.pptx
 
Lecture 8 data structures and algorithms
Lecture 8 data structures and algorithmsLecture 8 data structures and algorithms
Lecture 8 data structures and algorithms
 
Data Structures 4
Data Structures 4Data Structures 4
Data Structures 4
 
Trees in Data Structure
Trees in Data StructureTrees in Data Structure
Trees in Data Structure
 
Binary tree and operations
Binary tree and operations Binary tree and operations
Binary tree and operations
 
Chapter 5_Trees.pdf
Chapter 5_Trees.pdfChapter 5_Trees.pdf
Chapter 5_Trees.pdf
 
Binary tree
Binary treeBinary tree
Binary tree
 
UNIT-4 TREES.ppt
UNIT-4 TREES.pptUNIT-4 TREES.ppt
UNIT-4 TREES.ppt
 
Trees
TreesTrees
Trees
 
Final tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentationFinal tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentation
 
Trees in data structrures
Trees in data structruresTrees in data structrures
Trees in data structrures
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
Data structure tree- advance
Data structure tree- advanceData structure tree- advance
Data structure tree- advance
 

Recently uploaded

HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 

Recently uploaded (20)

HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 

Unit 4.1 (tree)

  • 1. UNIT-IV(Trees,Graphs)  Trees: Definitions and Concepts  Operationson Binary Trees  Representation of binary tree  Conversion of General Trees to Binary Trees  Representationsof Binary Trees  Tree Traversal.  Binary Search Trees: Representation and operations.  Heap Tree: definition, representation  Heap Sort.  Graphs: Introduction  Applicationsof graphs  Graph representations  graph traversals  Minimal SpanningTrees. S. Durga Devi , CSE, CBIT
  • 2. Trees S. Durga Devi , CSE, CBIT
  • 3. General View of a Tree root branches leaves S. Durga Devi , CSE, CBIT
  • 5. 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 called sub tree of the root.structure of a tree A B DC E F G K L H I J T1 T2 T3 S. Durga Devi , CSE, CBIT
  • 6. Tree Terminology Root: node without parent (A) Siblings: nodes share the same parent 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. 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 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 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. Subtree: tree consisting of a node and its descendants. Sibling: node have same parent . I,J,K has parent F. A B DC G HE F I J K subtree S. Durga Devi , CSE, CBIT
  • 7. • Path: a sequence of nodes and edges connecting a node with descendants. S. Durga Devi , CSE, CBIT
  • 8. • Height of a tree: • The height of tree is no of edges present in longest path of a tree • A leaf node will have a height of 0. • Height of a node is the number of edges on the longest path from the node to a leaf. • S. Durga Devi , CSE, CBIT Height of node A is 3 that is from A->C->D->E Not from A to G
  • 9. • 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 S. Durga Devi , CSE, CBIT Note: depth and height of the tree returns same value. But for individual nodes gives different values.
  • 10. - 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
  • 11. Tree ADT integer size() booleanisEmpty() objectIteratorelements() positionIteratorpositions() position root() position parent(p) positionIterator children(p)  booleanisInternal(p) -booleanisExternal(p) -booleanisRoot(p) -swapElements(p,q) -object replaceElement(p,o) Additional updatemethods may be defined by data structures implementing the Tree ADT
  • 12. 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 2 4 1 6 3 5 2 4 1 6 3 5 2 4 1 6 3 tree Not a tree Not a tree
  • 13. Types of trees 1. Binary tree 2. Binary search tree 3. Heap tree 4. AVL- trees 5. Red-Black trees 6. Splay trees 7. B- Trees S. Durga Devi , CSE, CBIT
  • 14. 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 containsa specially designed nodecalled 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 nodein binary tree has at most two children. (0,1,2) Example of binary tree Right sub tree A B C D E H I F G J K Left sub tree root Right sub tree left sub tree
  • 15. • Difference between tree and binary tree Trees 1.Tree never be empty 2. A node may have any no of children nodes. Binary tree 1. May be empty 2. A node may have at most two children 0, 1, or 2 Two 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
  • 16. Full binary tree A binary tree is a full binary tree, if it contains maximum possible number of nodes in all levels. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Level 0- 1node Level 1-2nodes Level 2-4 nodes 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 2 3 4 5 6 7 8 9 Level 0-1node Level 1-2 nodes Level 2- 4 nodes Level 3- 2 nodes K A B C D E H I F G J Not a CBTS. Durga Devi , CSE, CBIT
  • 17. 3. strict binary tree: every node in binary tree has exactly two children except the leaf nodes. S. Durga Devi , CSE, CBIT A B C D E H I F G
  • 18. Applications of trees  express trees used in compilers Huffman code trees used in data compression algorithms. B- trees used in data bases. S. Durga Devi , CSE, CBIT
  • 19. 1. linearsequential 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 Binary tree representation 1. linearsequential representation 2. Linked list
  • 20. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 A B D C . E G . . . . . F Sequential representation A C DB F E G 1 2 4 3 76 13 Example- linearsequential representation S. Durga Devi , CSE, CBIT
  • 21. Advantages of linear representation 1. Any nodecan be accessed from any other node by calculatingthe 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 representationis the only way to store a tree. disadvantages 1. Other than full binary tree, if u store any tree most of the memory locationsare empty. 2. Allows only static representation. There is no possibleway to enhance the size of the tree. 3. Inserting a new node and deletinga nodefrom it are inefficient with this representation becausethese require considerabledata movement up and down the array which demand excessive processing time. S. Durga Devi , CSE, CBIT
  • 22. struct node { /* a nodein 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 pointervariable root representsthe root of the tree. 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)plusan element field.  The space required by an n node binary tree is n * sizeof a node. S. Durga Devi , CSE, CBIT
  • 23. + - * A B DC 200 300 400 500 600 700 100 200 500 300 400 600 700 S. Durga Devi , CSE, CBIT
  • 24. 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
  • 25. 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
  • 26. int main() { // insert new node into a binary tree struct node * root=createNode(20); root->lchild=createNode(30); root->rchild=createNode(40); root->lchild->lchild=createNode(50); root->rchild->lchild=creatNode(60); return 0; } S. Durga Devi , CSE, CBIT 6050 4030 20
  • 27. Tree traversals void preorder(struct node *root) { if(root) { printf(“%d “,root->data); preorder(root->lchild); preorder(root->rchild); } } S. Durga Devi , CSE, CBIT 6050 4030 20 20 30 50 40 60
  • 28. S. Durga Devi , CSE, CBIT 6050 4030 20
  • 29. Inorder traversal void inorder(struct node*root) { if(root) { inorder(root->lchild); printf(“%d “,root->data); inorder(root->rchild); } } 50 S. Durga Devi , CSE, CBIT 6050 4030 20
  • 30. 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
  • 31. write a python program to implement insertion and traversal operations on binary tree S. Durga Devi , CSE, CBIT
  • 32. Conversion of general tree to binary tree S. Durga Devi , CSE, CBIT 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 binarty tree.
  • 33. S. Durga Devi , CSE, CBIT General Tree A B I H E F G C D root
  • 34. Properties of binary trees 1. In BT, the maximum number of nodes at level i, where i>=0 at level 0=20 =1 node at level 1= 21=2 nodes 2. The maximum no of nodes possible in a binary tree of height h is Nmax=2h+1-1 n= 2i 3. The minimum no of node possiblein a binary tree of height h is Nmin=h+1 If height=2 maximum no of nodes are 7 If height =3 minimum no of nodes are 3 4. The minimum no of nodes possibleat every level is only one node. When every parent node has on childsuch kind of tree is calledskew binary tree. Fig-b S. Durga Devi ,CSE,CBIT
  • 35. 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 nodesn0 = 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
  • 36. • Total no of binary tree possible with 3 nodes is- 5- A,B,C A B C 1 A B C 2 A B C 3 A B C 4 A B C 5 Representation of binary tree 1. linearsequential representation (using arrays). 2. linked representation (using linked list) S. Durga Devi ,CSE,CBIT
  • 37. BinarayTree traversals • This operationis used to visit each node in the tree exactly once. • The tree can be traversed in various ways. for a systematic traversal, it is betterto visit each node and its sub trees in the same fashion. • Followingare 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
  • 38. 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 nodein in order. 2. visit the root node. 3.Traverse the right sub tree of the root nodein in order. Postorder traversal 1.Traversethe left sub tree of the root nodein post order. 2. Traverse the right sub tree of the root nodein 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 continuein this manner, visiting the nodes at each new level from the leftmost node to the right most node. S. Durga Devi ,CSE,CBIT
  • 39. S. Durga Devi ,CSE,CBIT
  • 40. S. Durga Devi ,CSE,CBIT
  • 41. S. Durga Devi ,CSE,CBIT
  • 42. pre order of binary tree A B C D E H I F G J K Pre order- A,B,D,E,H,I,C,F,J,K,G S. Durga Devi ,CSE,CBIT
  • 43. In order of binary tree A B C D E H I F G J K Inorder- D,B,H,E,I,A,F,K,J,C,G S. Durga Devi ,CSE,CBIT
  • 44. In order of binary tree A B C D E H I F G J K Inorder- D,B,H,E,I,A,F,K,J,C,G S. Durga Devi ,CSE,CBIT
  • 45. Post order of binary tree A B C D E H I F G J K Post order- D,H,I,E,B,K,J,F,G,C,A S. Durga Devi ,CSE,CBIT
  • 46. Level order of binary tree A B C D E H I F G J K Level order- A,B,C,D,E,F,G,H,I,J,K S. Durga Devi ,CSE,CBIT
  • 47. 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
  • 48. Pre order for the following tree + - * A B C / D E Pre order- +,-,A,B,*,C,/,D,E. S. Durga Devi ,CSE,CBIT
  • 49. in order of the following tree + - * A B C / D E Pre order- +,-,A,B,*,C,/,D,E. In order- A,-,B,+,C,*,D,/,E
  • 50. post order of the following tree + - * A B C / D E Pre order- +,-,A,B,*,C,/,D,E. In order-A,-,B,+,C,*,D,/,E
  • 51. 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 nodehas 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. k All<K All>K S. Durga Devi , CSE, CBIT
  • 52. • The following are the bst( binary search trees) 18 15 20 12 17 25 35 45 5040 20 15 25 12 18 22 Its not a binary search tree because it fails to satisfy the property of 3 and 4 S. Durga Devi , CSE, CBIT
  • 53. Binary search tree representation • Binary search tree representation is same as binary tree representation • Refer binary tree representation. S. Durga Devi ,CSE,CBIT
  • 54. BST operations 1.create 2. insertion 3. deletion 4.findmax 5.findmin 6.search 7.display S. Durga Devi ,CSE,CBIT
  • 55. 1. Search operation on BST • Searching- supposewe 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
  • 56. Example- find a given key node in a following BST 20 15 25 12 18 22 Search node-22 22>20 S. Durga Devi ,CSE,CBIT
  • 57. 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 nodewith 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 2 8 1 4 3 a) Before insertion Insert node- 5 6 2 1 4 3 5 8 b) After inserting node 5 S. Durga Devi , CSE, CBIT
  • 58. Construct BST with following elements 19, 55,44,98,8,23,15,6,10,82,99 19 55 98 99 23 44 82 8 6 15 10 Root S. Durga Devi ,CSE,CBIT
  • 59. Deletion operation on BST • Anotherfrequentlyused operation on the BST is to deleteany node from it. This is slightly complicated one. • To delete a node from a binary search tree, there are three possible cases when we deletea node. case-1-if deleted nodeis a leaf nodeor node has no children, it can be deleted by making its parent pointers( left, right) to NULL. 30 25 40 20 35 45 30 25 40 20 45 a. Before deletion b. After deletionDeleted node-35 S. Durga Devi ,CSE,CBIT
  • 60. Case-2 if the deleted node has one child, either left child or right child, its parent pointer needs to be changed. 4 6 8 9 7 After deletion 8 6 7 9 4 1 Deleted node-1 S. Durga Devi ,CSE,CBIT
  • 61. S. Durga Devi ,CSE,CBIT
  • 62. S. Durga Devi ,CSE,CBIT
  • 63. case-3 • If deleted nodehas two children • First find out the inorder successor (X) of the deleted node( in order successor means the node which comes after the deleted nodeduring 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 replacethe data content in deleted node by the data of the x. 45 35 27 24 2916 20 45 2916 24 35 42 42 3327 x 33 S. Durga Devi ,CSE,CBIT
  • 64. 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
  • 65. • Write a program to implement BST with following operations i insertion ii deletion iii inorder iv postorder v preorder. S. Durga Devi ,CSE,CBIT
  • 66. Using Python S. Durga Devi ,CSE,CBIT
  • 67. # define a class for the node #inserting node in BST S. Durga Devi ,CSE,CBIT
  • 68. S. Durga Devi ,CSE,CBIT
  • 69. S. Durga Devi ,CSE,CBIT
  • 70. S. Durga Devi ,CSE,CBIT
  • 71. 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
  • 72. S. Durga Devi ,CSE,CBIT
  • 73. 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
  • 74. 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
  • 75. 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 additionalspace in each nodefor storing the left and right subtrees. S. Durga Devi ,CSE,CBIT
  • 76. Threaded binary tree • In linked list representation thereare more null links than actual pointers. If there are n nodes n+1 null links are present and total links are 2n. • To make use of these null pointersthreaded binary trees are introduced. Definition • A binary tree is said to be threadedbinary tree by making all right child pointersthat would normally be null point to the inorder successor of the node, and all the left child pointers that would normally be null point to the inorder predecessorof the node. Advantages • Inorder traversal can be donefaster without using stack. • Makes use of null pointersin binary tree. • Successor and predecessor can be find easily. S. Durga Devi ,CSE,CBIT
  • 77. Threaded binary tree… Threaded binary tree Binary tree S. Durga Devi ,CSE,CBIT
  • 78. Threaded Binary Tree • Threads are two types 1. One way threaded binary tree 2. Two way threaded binary tree 1. Threaded Binary Tree One-Way • Accordingly, in the one way threading of T, a thread will appear in the right field of a node and will point to the next node in the in-order traversal of T. • See the bellow example of one-way in-order threading. S. Durga Devi ,CSE,CBIT
  • 79. Threaded Binary Tree: One-Way Inorder of below tree is: D,B,F,E,A,G,C,L,J,H,K S. Durga Devi ,CSE,CBIT
  • 80. 2. Threaded Binary Tree Two-Way • In the two-way threading of T. • A thread will also appear in the left field of a node and will point to the preceding node in the in-order traversal of tree T. • Furthermore, the left pointer of the first node and the right pointer of the last node (in the in-order traversal of T) will contain the null value when T does not have a header node. S. Durga Devi ,CSE,CBIT
  • 81. Threaded Binary Tree • Bellow figure show two-way in-order threading. • Here, right pointer=next node of in-order traversal and left pointer=previous node of in-order traversal • Inorder of bellow tree is: D,B,F,E,A,G,C,L,J,H,K S. Durga Devi ,CSE,CBIT
  • 82. Threaded Binary Tree S. Durga Devi ,CSE,CBIT
  • 83. Memory representation of threaded binary tree • In memory representation we must be able to distinguish between thread and normal pointers. • Node structure represented with two additional boolean fields left thread and right thread to tree node. • If tree→leftthread==TRUE, then tree→leftchild contains a thread; otherwise, it contains false value. Similarly, if tree→rightthread == TRUE, then tree→rightchild contains a thread. Otherwise it contains a false value. Lefthtread Left child Data Right child Right thread S. Durga Devi ,CSE,CBIT
  • 85. Threaded Binary Tree Two-way Threading with Header node • Again two-way threading has left pointer of the first node and right pointer of the last node (in the inorder traversal of T) will contain the null value when T will point to the header nodes is called two-way threading with header node threaded binary tree. S. Durga Devi ,CSE,CBIT
  • 86. Threaded Binary Tree • Bellow figure to explain two-way threading with header node. S. Durga Devi ,CSE,CBIT
  • 87. Threaded Binary Tree • Bellow example of link representation of threading binary tree. • In-order traversal of bellow tree: G,F,B,A,D,C,E S. Durga Devi ,CSE,CBIT
  • 88. Threaded Binary Tree S. Durga Devi ,CSE,CBIT
  • 89. Priority queue ADT • Priority queueis abstract data type which is like a queue or stack data structurebut 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 operatingsystem 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
  • 90. Heaps • Priority queues are implemented using 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
  • 91. Min Heap Max Heap S. Durga Devi ,CSE,CBIT
  • 92. 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
  • 93. Binary Heaps: Array Implementation S. Durga Devi ,CSE,CBIT
  • 94. 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
  • 95. Example • Construct a min heap with following elements:10,6,20,5, 16, 17, 13,2 10 Insert 10 S. Durga Devi ,CSE,CBIT
  • 96. 10 Insert 6 6 6<10 swap with parent 10 S. Durga Devi ,CSE,CBIT
  • 97. 6 Insert 6 10 S. Durga Devi ,CSE,CBIT
  • 98. 6 Insert 20 10 20>6 need not swap 20 S. Durga Devi ,CSE,CBIT
  • 99. 6 Insert 5 10 5< 10 then swap 20 5 S. Durga Devi ,CSE,CBIT
  • 100. 6 Insert 5 5 5< 6 then swap 20 10 S. Durga Devi ,CSE,CBIT
  • 101. 5Insert 5 6 5< 6 then swap 20 10 S. Durga Devi ,CSE,CBIT
  • 102. 5Insert 16 6 16>6 need not swap 20 10 16 S. Durga Devi ,CSE,CBIT
  • 103. 5Insert 16 6 16>6 need not swap 20 10 16 S. Durga Devi ,CSE,CBIT
  • 104. 5 Insert 17 6 17<20 then swap 20 10 16 17 S. Durga Devi ,CSE,CBIT
  • 105. 5 Insert 17 6 17<20 then swap 17 10 16 20 S. Durga Devi ,CSE,CBIT
  • 106. 5Insert 13 6 13<17 then swap 17 10 16 20 13 S. Durga Devi ,CSE,CBIT
  • 107. 5Insert 13 6 13<17 then swap 13 10 16 20 17 S. Durga Devi ,CSE,CBIT
  • 108. 5 Insert 2 6 2<10 then swap 13 10 16 20 17 2 S. Durga Devi ,CSE,CBIT
  • 109. 5 Insert 2 6 2<6 then swap 13 2 16 20 17 10 S. Durga Devi ,CSE,CBIT
  • 110. 5 Insert 2 2 2<5 then swap 13 6 16 20 17 10 S. Durga Devi ,CSE,CBIT
  • 111. 2Insert 2 5 2<5 then swap 13 6 16 20 17 10 This process of moving the empty node towards the root is called percolate up S. Durga Devi ,CSE,CBIT
  • 112. 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
  • 115. 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
  • 116. Heap sort S. Durga Devi ,CSE,CBIT
  • 117. Why study 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
  • 118. 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
  • 119. Mapping into an array 19 1418 22 321 14 119 15 25 1723 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 • 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
  • 124. 19 1418 21 311 14 259 15 23 1722 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 S. Durga Devi ,CSE,CBIT
  • 129. 19 1418 11 39 14 15 22 1721 Continuethis process until tree is empty S. Durga Devi ,CSE,CBIT
  • 130. • 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