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

Adsaa Unit 1

The document explains AVL trees and Red-Black trees, detailing their properties, insertion, and deletion processes. AVL trees are height-balanced binary search trees that maintain balance through rotations after insertions and deletions, while Red-Black trees are self-balancing binary search trees that use color properties to ensure balance with fewer rotations. The document also compares the two tree types, highlighting that AVL trees are more strictly balanced, whereas Red-Black trees offer easier deletion and searching operations.

Uploaded by

hepsibadevireddy
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)
4 views

Adsaa Unit 1

The document explains AVL trees and Red-Black trees, detailing their properties, insertion, and deletion processes. AVL trees are height-balanced binary search trees that maintain balance through rotations after insertions and deletions, while Red-Black trees are self-balancing binary search trees that use color properties to ensure balance with fewer rotations. The document also compares the two tree types, highlighting that AVL trees are more strictly balanced, whereas Red-Black trees offer easier deletion and searching operations.

Uploaded by

hepsibadevireddy
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/ 44

UNIT-1

AVL TREE

AVL tree is a height-balanced binary search tree. That means, an AVL tree is also a binary search
tree but it is a balanced tree. A binary tree is said to be balanced if, the difference between the
heights of left and right sub trees of every node in the tree is either -1, 0 or +1. In other words, a
binary tree is said to be balanced if the height of left and right children of every node differ by
either-1, 0 or +1. In an AVL tree, every node maintains an extra information known as balance
factor.
Balance factor of a node is the difference between the heights of the left and right sub trees of that node.
The balance factor of a node is calculated either height of left sub-tree - height of right sub-tree (OR)
height of right sub-tree- height of left sub-tree.In the following explanation, we calculate as follows...

Balance factor=height Of Left Sub-tree- height-Of-Right-Sub-tree

AVL Tree Rotation

In AVL tree, after performing operations like insertion and deletion we need to check the balance
factor of every node in the tree. If every node satisfies the balance factor condition then we conclude
the operation otherwise we must make it balanced. Whenever the tree becomes imbalanced due to any
operation we use rotation operations to make the tree balanced.

a. Single Left Rotation (LL Rotation)


In LL Rotation, every node moves one position to left from the current position. To understand LL
Rotation, let us consider the following insertion operation

ADSAAUNIT-1[R-23] Page1
b. Single Right Rotation ( RR Rotation)

In RR Rotation, every node moves one position to right from the current position. To understand RR
Rotation, let us consider the following insertion operation in AVL Tree...

c. Left Right Rotation ( LR Rotation)

The LR Rotation is a sequence of single left rotation followed by a single right rotation. In LR Rotation,
at first, every node moves one position to the left and one position to right from the current position. To
understand LR Rotation, let us consider the following insertion operation in AVL Tree...

d. Right Left Rotation (RL Rotation)

The RL Rotation is sequence of single right rotation followed by single left rotation. In RL Rotation, at
first every node moves one position to right and one position to left from the current position. To
ADSAAUNIT-1[R-23] Page2
understand RL Rotation, let us consider the following insertion operation in AVL Tree...

Inserting a New Node in an AVL Tree


Insertion in an AVL tree is also done in the same way as it is done in a binary search tree. In the AVL
tree, the new node is always inserted as the leaf node. But the step of insertion is usually followed by
an additional step of rotation. Rotation is done to restore the balance of the tree. However, if
Insertion of the new node does not disturb the balance factor, that is, if the balance factor of every node
is still –1, 0, or 1, then rotations are not required.
Example: Construct an A V L Tree by inserting numbers from 1 to 8.

ADSAAUNIT-1[R-23] Page3
Insertion Algorithm:
Step1: Insert the node into the AVL tree like standard Binary Search Tree (BST) insertion.
Step2: After inserting node if the tree is balanced no need to perform rotations. Otherwise perform steps
3 to 4:
Step3: If the balance factor of the current node is > 1or < -1, perform the appropriate rotations to
balance the tree.
Step3.1: Left Rotation Case: Perform Right rotation
Step3.2: Right Rotation Case: Perform Left rotation
Step 3.3: Left-Right ( LR) Rotation Case: Perform a left rotation on the left child, then a right
rotation on the current node.
Step 3.4: Right-Left (RL) Rotation Case: Perform a right rotation on the right child, then a left
rotation on the current node.
Step4: After balancing, return the root of the sub-tree.
Step5: End Deletion

A node is always deleted as a leaf node. After deleting a node, the balance factors of the nodes get
changed. To rebalance the balance factor, suitable rotations are performed.

There are three cases for deleting node:


1: If the node to be deleted has two children, replace it with its in-order successor (or predecessor) and
delete the successor (or predecessor) node.
ADSAAUNIT-1[R-23] Page4
2: If the node to be deleted has one child, replace it with its child.
3: If the node to be deleted has no children, simply remove it.

Example:-

Delete7, 6, 5, 2 from the following AVL Tree

 Deletingelement7fromthetreeabove−
Since the element 7 is a leaf, we normally remove the element without disturbing any other node in the

tree

 Deleting element 6 from the out-put tree achieved−

However, element 6 is not a leaf node and has one child node attached to it. In this case, we replace
node 6 with its child node: node 5.


Deleting element 5 from the out-put tree achieved−
If we delete the element 5 further, we would have to apply the left rotations

The balance factor is disturbed after deleting the element 5, therefore we apply LL rotation (we can also

ADSAAUNIT-1[R-23] Page5
apply the LR rotation here).

Once the LL rotation is applied on path 1-2-4, the node 3 remains as it was supposed to be the right
child of node 2 ( which is now occupied by node 4 ) . Hence, the node is added to the right sub-tree of
the node 2 and as the left child of the node 4.

 Deleting element 2 from the remaining tree−

As mentioned in scenario 3, this node has two children. Therefore, we find its in-order successor that is
a leaf node (say, 3) and replace its value with the in-order successor.

RED-BLACK TREES
The red-Black tree is a binary search tree. The prerequisite of the red-black tree is that we should know
about the binary search tree. In a binary search tree, the values of the nodes in the left sub-tree should be less
than the value of the root node, and the values of the nodes in the right sub-tree should be greater than the
value of the root node.

Each node in the Red-black tree contains an extra bit that represents a color to ensure that the tree is balanced
during any operations performed on the tree like insertion, deletion, etc. In a binary search tree, the
searching, insertion and deletion take O(log 2n) time in the average case, O(1) in the best case and O(n) in
the worst case.

Let's understand the different scenarios of a binary search tree.

In the above tree, if we want to search the 80. We will first compare 80 with the root node. 80 is greater than
the root node, i.e., 10, so searching will be performed on the right sub-tree. Again, 80 is compared with 15;
80 is greater than 15, so we move to the right of the 15, i.e., 20. Now, we reach the leaf node 20, and 20 is

ADSAAUNIT-1[R-23] Page6
not equal to 80. Therefore, it will show that the element is not found in the tree. After each operation, the
search is divided into half. The above BST will take O(log n) time to search the element.

The above tree shows the right-skewed BST. If we want to search the 80 in the tree, we will compare 80 with
all the nodes until we find the element or reach the leaf node. So, the above right-skewed BST will
take O(n) time to search the element.

In the above BST, the first one is the balanced BST, whereas the second one is the unbalanced BST. We
conclude from the above two binary search trees that a balanced tree takes less time than an unbalanced tree
for performing any operation on the tree.

Therefore, we need a balanced tree, and the Red-Black tree is a self-balanced binary search tree. Now, the
question arises that why do we require a Red-Black tree if AVL is also a height-balanced tree. The Red-
Black tree is used because the AVL tree requires many rotations when the tree is large, whereas the Red-
Black tree requires a maximum of two rotations to balance the tree. The main difference between the AVL
tree and the Red-Black tree is that the AVL tree is strictly balanced, while the Red-Black tree is not
completely height-balanced. So, the AVL tree is more balanced than the Red-Black tree, but the Red-Black
tree guarantees O(log 2n) time for all operations like insertion, deletion, and searching.

Insertion is easier in the AVL tree as the AVL tree is strictly balanced, whereas deletion and searching are
easier in the Red-Black tree as the Red-Black tree requires fewer rotations.

As the name suggests that the node is either colored in Red or Black color. Sometimes no rotation is
required, and only re-coloring is needed to balance the tree.

Properties of Red-Black tree


o It is a self-balancing Binary Search tree. Here, self-balancing means that it balances the tree itself by
either doing the rotations or re-coloring the nodes.
o This tree data structure is named as a Red-Black tree as each node is either Red or Black in color. Every
node stores one extra information known as a bit that represents the color of the node. For example, 0 bit
denotes the black color while 1 bit denotes the red color of the node. Other information stored by the node
is similar to the binary tree, i.e., data part, left pointer and right pointer.
o In the Red-Black tree, the root node is always black in color.
o In a binary tree, we consider those nodes as the leaf which have no child. In contrast, in the Red-Black
tree, the nodes that have no child are considered the internal nodes and these nodes are connected to the
NIL nodes that are always black in color. The NIL nodes are the leaf nodes in the Red-Black tree.
o If the node is Red, then its children should be in Black color. In other words, we can say that there should
be no red-red parent-child relationship.
o Every path from a node to any of its descendant's NIL node should have same number of black nodes.

ADSAAUNIT-1[R-23] Page7
Is every AVL tree can be a Red-Black tree?

Yes, every AVL tree can be a Red-Black tree if we color each node either by Red or Black color. But every
Red-Black tree is not an AVL because the AVL tree is strictly height-balanced while the Red-Black tree is
not completely height-balanced.

Insertion in Red Black tree:

The following are some rules used to create the Red-Black tree:

1) If the tree is empty, then we create a new node as a root node with the color RED.
2) If the tree is not empty, then we create a new node as a leaf node with a color RED
3) If the parent of a new node is BLACK, then exit.
4) If the parent of a new node is RED, then we have to check the color of the parent's sibling of a
new node.
4a) If the color is BLACK, then we perform rotations and re-coloring.
4b) If the color is RED then we recolor the node. We will also check whether the parents' parent of a
new node is the root node or not; if it is not a root node, we will re-color and recheck the node.
Let's understand the insertion in the Red-Black tree.

10, 18, 7, 15, 16, 30, 25, 40, 60

Step 1: Initially, the tree is empty, so we create a new node having value 10. This is the first node of the tree,
so it would be the root node of the tree. As we already discussed, that root node must be black in color,
which is shown below:

Step 2: The next node is 18. As 18 is greater than 10 so it will come at the right of 10 as shown below.

We know the second rule of the Red Black tree that if the tree is not empty then the newly created node will
have the Red color. Therefore, node 18 has a Red color, as shown in the below figure:

Now we verify the third rule of the Red-Black tree, i.e., the parent of the new node is black or not. In the
above figure, the parent of the node is black in color; therefore, it is a Red-Black tree.

Step 3: Now, we create the new node having value 7 with Red color. As 7 is less than 10, so it will come at
the left of 10 as shown below.

ADSAAUNIT-1[R-23] Page8
Now we verify the third rule of the Red-Black tree, i.e., the parent of the new node is black or not. As we can
observe, the parent of the node 7 is black in color, and it obeys the Red-Black tree's properties.

Step 4: The next element is 15, and 15 is greater than 10, but less than 18, so the new node will be created at
the left of node 18. The node 15 would be Red in color as the tree is not empty.

The above tree violates the property of the Red-Black tree as it has Red-red parent-child relationship. Now
we have to apply some rule to make a Red-Black tree. The rule 4 says that if the new node's parent is Red,
then we have to check the color of the parent's sibling of a new node. The new node is node 15; the parent
of the new node is node 18 and the sibling of the parent node is node 7. As the color of the parent's sibling is
Red in color, so we apply the rule 4a. The rule 4a says that we have to recolor both the parent and parent's
sibling node. So, both the nodes, i.e., 7 and 18, would be re-colored as shown in the below figure.

We also have to check whether the parent's parent of the new node is the root node or not. As we can observe
in the above figure, the parent's parent of a new node is the root node, so we do not need to recolor it.
Step 5: The next element is 16. As 16 is greater than 10 but less than 18 and greater than 15, so node 16 will
come at the right of node 15. The tree is not empty; node 16 would be Red in color, as shown in the below
figure:

In the above figure, we can observe that it violates the property of the parent-child relationship as it has a
red-red parent-child relationship. We have to apply some rules to make a Red-Black tree. Since the new
node's parent is Red color, and the parent of the new node has no sibling, so rule 4a will be applied. The
rule 4a says that some rotations and re-coloring would be performed on the tree.
Since node 16 is right of node 15 and the parent of node 15 is node 18. Node 15 is the left of node 18. Here
we have an LR relationship, so we require to perform two rotations. First, we will perform left, and then we
will perform the right rotation. The left rotation would be performed on nodes 15 and 16, where node 16 will

ADSAAUNIT-1[R-23] Page9
move upward, and node 15 will move downward. Once the left rotation is performed, the tree looks like as
shown in the below figure:

In the above figure, we can observe that there is an LL relationship. The above tree has a Red-red conflict,
so we perform the right rotation. When we perform the right rotation, the median element would be the root
node. Once the right rotation is performed, node 16 would become the root node, and nodes 15 and 18 would
be the left child and right child, respectively, as shown in the below figure.

After rotation, node 16 and node 18 would be re-colored; the color of node 16 is red, so it will change to
black, and the color of node 18 is black, so it will change to a red color as shown in the below figure:

Step 6: The next element is 30. Node 30 is inserted at the right of node 18. As the tree is not empty, so the
color of node 30 would be red.

The color of the parent and parent's sibling of a new node is Red, so rule 4b is applied. In rule 4b, we have to
do only re-coloring, i.e., no rotations are required. The color of both the parent (node 18) and parent's sibling
(node 15) would become black, as shown in the below image.

ADSAAUNIT-1[R-23] Page10
We also have to check the parent's parent of the new node, whether it is a root node or not. The parent's
parent of the new node, i.e., node 30 is node 16 and node 16 is not a root node, so we will recolor the node
16 and changes to the Red color. The parent of node 16 is node 10, and it is not in Red color, so there is no
Red-red conflict.

Step 7: The next element is 25, which we have to insert in a tree. Since 25 is greater than 10, 16, 18 but less
than 30; so, it will come at the left of node 30. As the tree is not empty, node 25 would be in Red color. Here
Red-red conflict occurs as the parent of the newly created is Red color.
Since there is no parent's sibling, so rule 4a is applied in which rotation, as well as re-coloring, are
performed. First, we will perform rotations. As the newly created node is at the left of its parent and the
parent node is at the right of its parent, so the RL relationship is formed. Firstly, the right rotation is
performed in which node 25 goes upwards, whereas node 30 goes downwards, as shown in the below figure.

After the first rotation, there is an RR relationship, so left rotation is performed. After right rotation, the
median element, i.e., 25 would be the root node; node 30 would be at the right of 25 and node 18 would be at
the left of node 25.

ADSAAUNIT-1[R-23] Page11
Now re-coloring would be performed on nodes 25 and 18; node 25 becomes black in color, and node 18
becomes red in color.

Step 8: The next element is 40. Since 40 is greater than 10, 16, 18, 25, and 30, so node 40 will come at the
right of node 30. As the tree is not empty, node 40 would be Red in color. There is a Red-red conflict
between nodes 40 and 30, so rule 4b will be applied.

As the color of parent and parent's sibling node of a new node is Red so re-coloring would be performed. The
color of both the nodes would become black, as shown in the below image.
After re-coloring, we also have to check the parent's parent of a new node, i.e., 25, which is not a root node,
so re-coloring would be performed, and the color of node 25 changes to Red.
After re-coloring, red-red conflict occurs between nodes 25 and 16. Now node 25 would be considered as the
new node. Since the parent of node 25 is red in color, and the parent's sibling is black in color, rule 4a would
be applied. Since 25 is at the right of the node 16 and 16 is at the right of its parent, so there is an RR
relationship. In the RR relationship, left rotation is performed. After left rotation, the median element 16
would be the root node, as shown in the below figure.

After rotation, re-coloring is performed on nodes 16 and 10. The color of node 10 and node 16 changes to
Red and Black, respectively as shown in the below figure.

ADSAAUNIT-1[R-23] Page12
After rotation, the re-coloring is performed on nodes 30 and 40. The color of node 30 would become Red,
while the color of node 40 would become black.

The above tree is a Red-Black tree as it follows all the Red-Black tree properties.

Deletion in Red Back tree


Let's understand how we can delete the particular node from the Red-Black tree.

The following are the rules used to delete the particular node from the tree:

Step 1: First, we perform BST rules for the deletion.

Step 2:

Case 1: if the node is Red leaf node which is to be deleted, we simply delete it.

Case 2: If the root node is also Double Black (DB), then simply remove the double black and make it a
single black.

ADSAAUNIT-1[R-23] Page13
Case 3: If the Double Black's (DB’s) sibling is black and both of its children are black.

o Remove the double black node.


o Add the color of the node to the parent (P) node.

1. If the color of P is red then it becomes black.


2. If the color of P is black, then it becomes double black.

Case 4: If double black's sibling is Red.

o Swap the color of its parent and its sibling.


o Rotate the parent node in the double black's direction.
o Reapply cases.
Case 5: If double black's sibling is black, sibling's child who is far from the double black is black, but near
child to double black is red.

o Swap the color of double black's sibling and the sibling child which is nearer to the double black node.
o Rotate the sibling in the opposite direction of the double black.
o Apply case 6
Case 6: If double black's sibling is black, far child is Red

o Swap the color of Parent and its sibling node.


o Rotate the parent towards the Double black's direction
o Remove Double black
o Change the Red color to black.

Let's understand case 1 through an example.

Suppose we want to delete node 30 from the tree, which is given below.

ADSAAUNIT-1[R-23] Page14
Initially, we are having the address of the root node. First, we will apply BST to search the node. Since 30 is
greater than 10 and 20, which means that 30 is the right child of node 20. Node 30 is a leaf node and Red in
color, so it is simply deleted from the tree.

If we want to delete the internal node that has one child. First, replace the value of the internal node with the
value of the child node and then simply delete the child node.

Let's take another example in which we want to delete the internal node, i.e., node 20.

We cannot delete the internal node; we can only replace the value of that node with another value. Node 20
is at the right of the root node, and it is having only one child, node 30. So, node 20 is replaced with a value
30, but the color of the node would remain the same, i.e., Black. In the end, node 20 (leaf node) is deleted
from the tree.

If we want to delete the internal node that has two child nodes. In this case, we have to decide from which we
have to replace the value of the internal node (either left sub-tree or right sub-tree). We have two ways:

o In-order predecessor: Largest value that exists in the left sub-tree of the node to be deleted.
o In-order successor: Smallest value that exists in the right sub-tree of the node to be deleted.
Suppose we want to delete node 30 from the tree, which is shown below:

ADSAAUNIT-1[R-23] Page15
Node 30 is at the right of the root node. In this case, we will use the in-order successor. The value 38 is the
smallest value in the right sub-tree, so we will replace the value 30 with 38, but the node would remain the
same, i.e., Red. After replacement, the leaf node, i.e., 30, would be deleted from the tree. Since node 30 is a
leaf node and Red in color, we need to delete it (we do not have to perform any rotations or any re-coloring).

Case 2 and Case 3:

Let's understand this case through an example.

Suppose we want to delete node 15 in the below tree.

We cannot simply delete node 15 from the tree as node 15 is Black in color. Node 15 has two children,
which are nil. So, we replace the 15 value with a nil value. As node 15 and nil node are black in color, the
node becomes double black after replacement, as shown in the below figure.

In the above tree, we can observe that the double black's sibling is black in color and its children are nil,
which are also black. As the double black's sibling and its children have black so it cannot give its black
color to neither of these. Now, the double black's parent node is Red so double black's node add its black
color to its parent node. The color of the node 20 changes to black while the color of the nil node changes to
a single black as shown in the below figure.

ADSAAUNIT-1[R-23] Page16
After adding the color to its parent node, the color of the double black's sibling, i.e., node 30 changes to red
as shown in the below figure.

In the above tree, we can observe that there is no longer double black's problem exists, and it is also a Red-
Black tree.

Case 4:

Let's understand this case through an example.

Suppose we want to delete node 15.

Initially, the 15 is replaced with a nil value. After replacement, the node becomes double black. Since double
black's sibling is Red so color of the node 20 changes to Red and the color of the node 30 changes to Black.

Once the swapping of the color is completed, the rotation towards the double black would be performed. The
node 30 will move upwards and the node 20 will move downwards as shown in the below figure.

In the above tree, we can observe that double black situation still exists in the tree. It satisfies the case 3 in
which double black's sibling is black as well as both its children are black. First, we remove the double black
from the node and add the black color to its parent node. At the end, the color of the double black's sibling,

ADSAAUNIT-1[R-23] Page17
i.e., node 25 changes to Red as shown in the figure.

In the above tree, we can observe that the double black situation has been resolved. It also satisfies the
properties of the Red Black tree.

Case 5:

Suppose we want to delete the node 1 in the below tree.

First, we replace the value 1 with the nil value. The node becomes double black as both the nodes, i.e., 1 and
nil are black. It satisfies the case 3 that implies if DB's sibling is black and both its children are black. First,
we remove the double black of the nil node. Since the parent of DB is Black, so when the black color is
added to the parent node then it becomes double black. After adding the color, the double black's sibling
color changes to Red as shown below.

We can observe in the above screenshot that the double black problem still exists in the tree. So, we will
reapply the cases. We will apply case 5 because the sibling of node 5 is node 30, which is black in color, the
child of node 30, which is far from node 5 is black, and the child of the node 30 which is near to node 5 is
Red. In this case, first we will swap the color of node 30 and node 25 so the color of node 30 changes to Red
and the color of node 25 changes to Black as shown below.

ADSAAUNIT-1[R-23] Page18
Once the swapping of the color between the nodes is completed, we need to rotate the sibling in the opposite
direction of the double black node. In this rotation, the node 30 moves downwards while the node 25 moves
upwards as shown below.

As we can observe in the above tree that double black situation still exists. So, we need to case 6. Let's first
see what is case 6.

Case 6:

Now we will apply case 6 in the above example to solve the double black's situation.

In the above example, the double black is node 5, and the sibling of node 5 is node 25, which is black in
color. The far child of the double black node is node 30, which is Red in color as shown in the below figure:

First, we will swap the colors of Parent and its sibling. The parent of node 5 is node 10, and the sibling node
is node 25. The colors of both the nodes are black, so there is no swapping would occur.

In the second step, we need to rotate the parent in the double black's direction. After rotation, node 25 will
move upwards, whereas node 10 will move downwards. Once the rotation is performed, the tree would like,
as shown in the below figure:

ADSAAUNIT-1[R-23] Page19
In the next step, we will remove double black from node 5 and node 5 will give its black color to the far
child, i.e., node 30. Therefore, the color of node 30 changes to black as shown in the below figure.

BINARY HEAPS

A binary heap is a complete binary tree in which every node satisfies the heap property which states
that:
If B is a child of A,then key(A) ≥ key(B)

This implies that elements at every node will be either greater than or equal to the element at its left
and right child. Thus, the root node has the highest key value in the heap. Such a heap is commonly
known as a max-heap.

Alternatively, elements at every node will be either less than or equal to the element at its left and
right child. Thus, the root has the lowest key value. Such a heap is called a min-heap

ADSAAUNIT-1[R-23] Page20
The properties of binary heaps are given as follows:
 Since a heap is defined as a complete binary tree, all its elements can be stored
sequentially in an array. It follows the same rules as that of a complete binary tree. That
is, if an element is at position i in the array, and then its left child is stored at position 2i
and its right child at position 2i+1. Conversely, an element at position i have its parent
stored at position i/2.
 Being a complete binary tree, all the levels of the tree except the last level are
completely filled.
 The height of a binary tree is given as log2n, where n is the number of elements.
 Heaps(also known as partially ordered trees) are a very popular data structure for
implementing priority queues.

Example:-
Build a max heap H from the given set of numbers: 45, 36, 54,27, 63,72, 61, and18. Also draw
the memory representation of the heap.

Inserting a New Element in a Binary Heap


Consider a max heap H with n elements. Inserting a new value into the heap is done in the
following two steps:

ADSAAUNIT-1[R-23] Page21
1. Add the new value at the bottom of H in such away that H is still a complete binary tree
but not necessarily a heap.
2. Let the new value rise to its appropriate place in H so that H now becomes a heap as
well. To do this, compare the new value with its parent to check if they are in the correct
order. If they are, then the procedure halts, else the new value and its parent’s value are
swapped and Step 2 is repeated.

The first step says that insert the element in the heap so that the heap is a complete binary
tree. So, insert the new value as the right child ofnode27 in the heap. This is illustrated in

Now, as per the second step, let the new value rise to its appropriate place in H so that H
becomes a heap as well. Compare 99 with its parent node value. If it is less than its
parent’s value, then the new node is in its appropriate place and H is a heap. If the new
value is greater than that of its parent’s node, then swap the two values. Repeat the whole
process until H becomes a heap. This is illustrated in Fig.

Deleting an Element from a Binary Heap

Consider a max heap H having n elements. An element is always deleted from the root of
the heap. So, deleting an element from the heap is done in the following three steps:
2. Replace the root node’s value with the last node’s values of that H is still a complete
binary tree but not necessarily a heap.
3. Delete the last node.
4. Sink down the new root node’s value so that H satisfies the heap property. In this step,
interchange the root node’s value with its child node’s value (whichever is largest among
its children).

ADSAAUNIT-1[R-23] Page22
Example:-
Consider the binary heap tree

If we want to delete the root value i.e the value 54 in the heap tree. Here, the value of root node =54
and the value of the last node = 11. So, replace 54 with 11 and delete the last node.

ADSAAUNIT-1[R-23] Page23
GRAPHS

Definition
A graph G is defined as an ordered set (V, E), where V(G) represents the set of vertices and E(G)
represents the edges that connect these vertices.

Graph Terminology

Vertex
Individual data element of a graph is called as Vertex. Vertex is also known as node. In the
given example graph, A, B, C, D & E are known as vertices.

Edge
An edge is a connecting link between two vertices. Edge is also known as Arc. An edge is
represented as (starting Vertex, ending Vertex). For example, in the graph the link between
vertices A and B is represented as (A, B). In the example graph, there are 7 edges (i.e., (A, B),
(A, C), (A, D), (B, D), (B, E), (C, D), (D, E)).

Adjacency− Two nodes or vertices are adjacent if they are connected to each other through an
edge. In the following example, B is adjacent to A, C is adjacent to B, and so on.

ADSAAUNIT-1[R-23] Page24
Path − Path represents a sequence of edges between the two vertices. In the following example,
ABCD represents a path from A to D.

Closed Path
A path will be called as closed path if the initial node is same as terminal node. A path will be
closed path if V0=VN.

Simple Path
If all the nodes of the graph are distinct with an exception V0=VN, then such path P is called as
closed simple path.

Cycle
A cycle can be defined as the path which has no repeated edges or vertices except the first and
last vertices.

Connected Graph
A connected graph is the one in which some path exists between every two vertices (u, v) in V.
There are no isolated nodes in connected graph.

Complete Graph
A complete graph is the one in which every node is connected with all other nodes. A complete
graph contain n(n-1)/2 edges where n is the number of nodes in the graph.

Weighted Graph
In a weighted graph, each edge is assigned with some data such as length or weight. The weight
of an edge e can be given as w(e) which must be a positive (+) value indicating the cost of
traversing the edge.

Degree of the Node


A degree of anode is the number of edges that are connected with that node. A node with degree
0 is called as isolated node.

TYPESOF GRAPES
Graphs are two types
i. Directed graph
ii. Undirected graph

i. Directed Graphs
A directed graph G, also known as a digraph, is a graph in which every edge has a direction
assigned to it. An edge of a directed graph is given as an ordered pair (u, v) of nodes in G. For an
edge (u, v),
a. The edge begins at u and terminates at v.

ADSAAUNIT-1[R-23] Page25
b. u is known as the origin or initial point of e. Correspondingly, v is known as the destination or
terminal point of e.
c. u is the predecessor of v. Correspondingly, v is the successor of u.
d. Nodes u and v are adjacent to each other.

ii. Undirected Graph


An undirected graph is a graph in which all the edges are bi-directional i.e. the edges do not point
in any specific direction.

REPRESENTATION OF GRAPHS
There are three common ways of storing graphs in the computer’ smemory.They are:
i. Sequential representation by using an adjacency matrix.
ii. Linked representation by using an adjacency list that stores the neighbors of a node using a
linked list.

Adjacency Matrix Representation


An adjacency matrix is used to represent which nodes are adjacent to one another. By definition,
two nodes are said to be adjacent if there is an edge connecting them. In a directed graph G, if
node v is adjacent to node u, then there is definitely an edge from u to v. That is, if v is adjacent
to u, we can get from u to v by traversing one edge. For any graph G having n nodes, the
adjacency matrix will have the dimension of n X n.

In an adjacency matrix, the rows and columns are labeled by graph vertices. An entry aij in the
adjacency matrix will contain 1, if vertices vi and vj are adjacent to each other. However, if the
nodes are not adjacent, a i, j will be set to zero. Since an adjacency matrix contains only 0s and
1s, it is called a bit matrix or a Boolean matrix. The entries in the matrix depend on the ordering
of the nodes in G. Therefore, a change in the order of nodes will result in a different adjacency

ADSAAUNIT-1[R-23] Page26
matrix. Figure shows some graphs and their corresponding adjacency matrices.

Adjacency List Representation


An adjacency list is another way in which graphs can be represented in the computer’s memory.
This structure consists of a list of all nodes in G. Furthermore, every node is in turn linked to its
own list that contains the names of all other nodes that are adjacent to it.
The key advantages of using an adjacency list are:
a. It is easy to follow and clearly shows the adjacent nodes of a particular node.
b. It is often used for storing graphs that have a small-to-moderate number of edges. That is, an
adjacency list is preferred for representing sparse graphs in the computer’s memory; otherwise,
an adjacency matrix is a good choice.
c. Adding new nodes in G is easy and straightforward when G is represented using an adjacency
list. Adding new nodes in an adjacency matrix is a difficult task, as the size of the matrix needs
to be changed and existing nodes may have to be reordered.

Consider the graph given in Fig., and see how its adjacency list is stored in the memory. For a
directed graph, the sum of the lengths of all adjacency lists is equal to the number of edges in G.
However, for an undirected graph, the sum of the lengths of all adjacency lists is equal to twice
the number of edges in G because an edge (u, v) means an edge from node u to v as well as an
edge from v to u. Adjacency lists can also be modified to store weighted graphs. Let us now see
an adjacency list for an undirected graph as well as a weighted graph.

ADSAAUNIT-1[R-23] Page27
ADSAAUNIT-1[R-23] Page28
GRAPH TRAVERSAL ALGORITHMS

By traversing a graph, we mean the method of examining the nodes and edges of the graph. There
are two standard methods of graph traversal. These two methods are:
1. Breadth-First Search
2. Depth-First Search

Breadth-First Search Algorithm (BFS):


Breadth-first search (BFS) is a graph search algorithm that begins at the root node and explores
all the neighboring nodes. Then for each of those nearest nodes, explores their unexplored
neighbor nodes, and so on, until it finds the goal. That is, we start examining the node A and then
all the neighbors of A are examined. In the next step, we examine the neighbors of neighbors of
A, so on and so forth. This means that we need to track the neighbors of the node and guarantee
that every node in the graph is processed and no node is processed more than once. This is
accomplished by using a queue that will hold the nodes that are waiting for further processing
and a variable STATUS to represent the current state of the node.
Example:-

ADSAAUNIT-1[R-23] Page29
ADSAAUNIT-1[R-23] Page30
ADSAAUNIT-1[R-23] Page31
Depth-First Search Algorithm(DFS)
The depth-first search algorithm progresses by expanding the starting node of G and then going
deeper and deeper until the goal node is found, or until a node that has no children is
encountered. When a dead-end is reached, the algorithm backtracks, returning to the most recent
node that has not been completely explored.
In other words, depth-first search begins at a starting node A which becomes the current node.
Then, it examines each node N along a path P which begins at A. That is, we process a neighbor
of A, then a neighbor of neighbor of A, and so on. During the execution of the algorithm, if we
reach a path that has a node N that has already been processed, then we backtrack to the current
node. Otherwise, the unvisited (unprocessed) node becomes the current node. Depth-first search
are implemented by using stack.

ADSAAUNIT-1[R-23] Page32
Example:-

ADSAAUNIT-1[R-23] Page33
ADSAAUNIT-1[R-23] Page34
ADSAAUNIT-1[R-23] Page35
Algorithm for Depth-First Search(DFS):

CONNECTED GRAPH: A Graph G=( V, E ) in which there is path between each pair of vertices

is termed as a connected graph. A graph which is not connected is called disconnected graph.

a. Connected Graph b. disconnected graph

CONNECTED COMPONENT

If graph is disconnected graph then the graph consists of more than one connected sub graphs,
each connected sub graph of that graph is a termed as Connected component.

For example in the graph shown below, {0, 1, 2} form a connected component and {3, 4} form
another connected component.

ADSAAUNIT-1[R-23] Page36
Characteristics of Connected Component:

 A connected component is a set of vertices in a graph that are connected to each other.
 A graph can have multiple connected components.
 In side a component, each vertex is reachable from every other vertex in that component.

One Connected Component


In this example, the given undirected graph has one connected component:

More Than One Connected Component


In this example, the undirected graph has three connected components:

BI-CONNECTED COMPONENTS

A bi-connected is a maximal sub graph in which any two vertices are connected to each other by
at least two disjoint paths, meaning the removal of any single vertex and its associated edges
does not disconnect the sub graph. In other words, it is a component of the graph that remains
connected even after the removal of any single vertex.

Key Concepts:
1. Bi connected Graph: A graph is bi connected if it is connected and does not contain any
articulation points (vertices that, if removed, would disconnect the graph).
2. Articulation Points: These are vertices that, when removed, increase the number of
connected components in the graph. Bi connected components are formed by removing
these points.
3. Bi connected Components: Also known as blocks, these are maximal sub graphs where
any two vertices are connected by two distinct paths. A graph can have multiple bi
connected components, connected to each other at articulation points.

ADSAAUNIT-1[R-23] Page37
Euler Path and Circuit
The Euler path is a path, by which we can visit every edge exactly once. We can use the same
vertices for multiple times.

The Euler Circuit is a special type of Euler path. When the starting vertex of the Euler path is
also connected with the ending vertex of that path, then it is called the Euler Circuit.

ADSAAUNIT-1[R-23] Page38
To detect the path and circuit, we have to follow these conditions−
 The graph must be connected.
 When exactly two vertices have odd degree, it is a Euler Path.
 Now when no vertices of an undirected graph have odd degree, then it is a Euler Circuit.

ADSAAUNIT-1[R-23] Page39
BFS Algorithm
The steps involved in the BFS algorithm to explore a graph are given as follows -

Step 1: SET STATUS = 1 (ready state) for each node in G

Step 2: Enqueue the starting node A and set its STATUS = 2 (waiting state)

Step 3: Repeat Steps 4 and 5 until QUEUE is empty

Step 4: Dequeue a node N. Process it and set its STATUS = 3 (processed state).

Step 5: Enqueue all the neighbours of N that are in the ready state (whose
STATUS = 1) and set their STATUS = 2(waiting state)

[END OF LOOP]

Step 6: EXIT

Example of BFS algorithm


Now, let's understand the working of BFS algorithm by using an example. In the example
given below, there is a directed graph having 7 vertices.

In the above graph, minimum path 'P' can be found by using the BFS that will start from
Node A and end at Node E. The algorithm uses two queues, namely QUEUE1 and
QUEUE2. QUEUE1 holds all the nodes that are to be processed, while QUEUE2 holds all
the nodes that are processed and deleted from QUEUE1.

Now, let's start examining the graph starting from Node A.

Step 1 - First, add A to queue1 and NULL to queue2.

ADSAAUNIT-1[R-23] Page40
QUEUE1 = {A}

QUEUE2 = {NULL}

Step 4 - Now, delete node D from queue1 and add it into queue2. Insert all
neighbors of node D to queue1. The only neighbor of Node D is F since it is
already inserted, so it will not be inserted again.

QUEUE1 = {C, F}

QUEUE2 = {A, B, D}

Step 5 - Delete node C from queue1 and add it into queue2. Insert all neighbors of node C
to queue1.

QUEUE1 = {F, E, G}

QUEUE2 = {A, B, D, C}

Step 5 - Delete node F from queue1 and add it into queue2. Insert all neighbors of node F
to queue1. Since all the neighbors of node F are already present, we will not insert them
again.

QUEUE1 = {E, G}

QUEUE2 = {A, B, D, C, F}

Step 6 - Delete node E from queue1. Since all of its neighbors have already been added,
so we will not insert them again. Now, all the nodes are visited, and the target node E is
encountered into queue2.

QUEUE1 = {G}

QUEUE2 = {A, B, D, C, F, E}

Complexity of BFS algorithm


Time complexity of BFS depends upon the data structure used to represent the graph. The
time complexity of BFS algorithm is O(V+E), since in the worst case, BFS algorithm
explores every node and edge. In a graph, the number of vertices is O(V), whereas the
number of edges is O(E).

The space complexity of BFS can be expressed as O(V), where V is the number of
vertices.

ADSAAUNIT-1[R-23] Page41
DFS Algorithm

Step 1: SET STATUS = 1 (ready state) for each node in G

Step 2: Push the starting node A on the stack and set its STATUS = 2 (waiting
state)

Step 3: Repeat Steps 4 and 5 until STACK is empty

Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed state)

Step 5: Push on the stack all the neighbors of N that are in the ready state
(whose STATUS = 1) and set their STATUS = 2 (waiting state)

[END OF LOOP]

Step 6: EXIT

Example of DFS algorithm

Now, let's understand the working of the DFS algorithm by using an example. In the
example given below, there is a directed graph having 7 vertices.

DFS algorithm

Now, let's start examining the graph starting from Node H.

Step 1 - First, push H onto the stack.


ADSAAUNIT-1[R-23] Page42
STACK: H

Step 2 - POP the top element from the stack, i.e., H, and print it. Now, PUSH all the
neighbors of H onto the stack that are in ready state.

Print: H STACK: A

Step 3 - POP the top element from the stack, i.e., A, and print it. Now, PUSH all the
neighbors of A onto the stack that are in ready state.

Print: A

STACK: B, D

Step 4 - POP the top element from the stack, i.e., D, and print it. Now, PUSH all the
neighbors of D onto the stack that are in ready state.

Print: D

STACK: B, F

Step 5 - POP the top element from the stack, i.e., F, and print it. Now, PUSH all the
neighbors of F onto the stack that are in ready state.

Print: F

STACK: B

Step 6 - POP the top element from the stack, i.e., B, and print it. Now, PUSH all the
neighbors of B onto the stack that are in ready state.

Print: B

STACK: C

Step 7 - POP the top element from the stack, i.e., C, and print it. Now, PUSH all the
neighbors of C onto the stack that are in ready state.

Print: C

STACK: E, G

Step 8 - POP the top element from the stack, i.e., G and PUSH all the neighbors of G onto
the stack that are in ready state.

Print: G
ADSAAUNIT-1[R-23] Page43
STACK: E

Step 9 - POP the top element from the stack, i.e., E and PUSH all the neighbors of E onto
the stack that are in ready state.

Print: E

STACK:

Now, all the graph nodes have been traversed, and the stack is empty.

Complexity of Depth-first search algorithm

The time complexity of the DFS algorithm is O(V+E), where V is the number of vertices
and E is the number of edges in the graph.

The space complexity of the DFS algorithm is O(V).

ADSAAUNIT-1[R-23] Page44

You might also like