0% found this document useful (0 votes)
34 views110 pages

Unit 4

Uploaded by

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

Unit 4

Uploaded by

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

Course Name: DATA STRUCTURES

(20CS21001)
UNIT- I
Data Abstraction, Performance analysis- time complexity and space complexity, Asymptotic Notation-Big O, Omega and Theta notations.

Introduction to Linear and Non Linear data structures: Circularly linked lists-Operations for Circularly linked lists, Doubly Linked Lists- Operations-
Insertion, Deletion. Representations of array-row major and column major, Sparse matrices-array and linked representations.
UNIT- II
Stack ADT, definition, operations, linked list implementation, Application of stack – Tower of Hanoi, Parenthesis Checker iterative and recursion
implementation.
Queue ADT, definition and operations, linked list implementation, Circular queues- Insertion and deletion operations, Deque (Double ended queue)
ADT, array and linked implementations.
UNIT- III
Trees – Terminology, Representation of Trees, Binary tree ADT, Properties of Binary Trees, Binary Tree Representations-array and linked
representations, Binary Tree traversals, Threaded binary trees.
Max Priority Queue ADT - implementation-Max Heap-Definition, Insertion into a Max Heap, Deletion from a Max Heap.
Sorting- Merge sort, Heap Sort, Radix Sort, Binary Insertion sort, Comparison of Sorting methods.
UNIT- IV
Search Trees - Binary Search Trees, Definition, Operations- Searching, Insertion and Deletion, AVL Trees- Definition and Examples, Insertion into an
AVL Tree

B-Trees - Definition, B-Tree of order m, operations-Insertion and Searching, Introduction to Red-Black and Splay Trees, Comparison of Search Trees.
UNIT-V
Graphs – Introduction, Definition, Terminology, Graph ADT, Graph Representations- Adjacency matrix, Adjacency lists, Adjacency multi lists, Graph
traversals- DFS and BFS.
Static Hashing-Introduction, hash tables, hash functions, Overflow Handling.

2
Syllabus

3
TEXTBOOK
1. Fundamentals of Data structures in C, 2nd
Edition, E.Horowitz, S.Sahni and Susan
Anderson-Freed, Universities Press.

REFERENCE BOOK(S)
1. Data structures and Algorithm Analysis in C,
2nd edition, M.A.Weiss, Pearson.
2. Data Structures using C, R.Thareja, Oxford
University Press.
3. Data structures: A Pseudocode Approach
with C, 2nd edition, R.F.Gilberg And
B.A.Forouzan, Cengage Learning.
4. Data Structures using C, A.M.Tanenbaum,Y.
Langsam, M.J.Augenstein, Pearson.
5. Data structures and Program Design in C,
2nd edition, R.Kruse, C.L.Tondo and
B.Leung,Pearson. 4
Assignment should not be

5
UNIT- IV
Search Trees:-
(i) Binary Search Trees, Definition, Operations-
Searching, Insertion and Deletion.
(ii) AVL Trees- Definition and Examples, Insertion into
an AVL Tree

(iii)B-Trees :- Definition, B-Tree of order m, operations-


Insertion and Searching,
(iv) Introduction to Red-Black and Splay Trees,
Comparison of Search

6
Search Trees:- A search tree is a tree data structure used for locating
specific keys from within a set
i. Binary search tree.
ii. B-tree.
iii. (a,b)-tree.
iv. Ternary search tree.
Binary Search Tree:- Binary search tree is one type of binary tree. A
binary search tree that may be empty. If a BST is Non-empty then
satisfies the following properties.

1. Every node has a value and no two elements (node) have the same
value, i.e in a Binary SerachTree, all the node’s values are different.

2. The values in the left subtree are smaller than the value of its root
node.

3. The values in the right subtree are greater than the value of the root
node.

k
4. The left and right subtree of the root is also a binary search tree.

All<K All>K
7
• Identify whether The following trees are bst( binary search trees) or not.

18 35

15 20 45

12 17 25
40 50
Tree-1
Tree-2
20
Tree-1 IS BST
Tree-2 IS BST
15 25 Tree-3 IS NOT BST Its not a binary search
tree because it fails to satisfy
the property of 3 and 4
12 18 22
Tree-3

8
A binary search tree with 7 nodes.

From the above tree


1. Root Node:- The topmost node. 100 is a root node.
3. Leaf Nodes:- The bottom-most nodes or the node with no reference
link. 10, 60, 150, 300 are leaf nodes.
2. Internal Nodes:- The nodes intermediate between root and the leaf
node. 50, 200 are intermediate nodes.

9
What is the need for a binary search tree?
If we arrange the data based on the above rules, we can effectively
manipulate them.

From the above tree If we need to search for element 10,


Check if the root node has the value 10. root node value = 100. 10 <
100. Hence 10 should be present in the left subtree (the right subtree
must have values > 100). So we can skip the entire right subtree from
the search.

1. root's key value = 100. 10 < 100.


2. So we can skip the right subtree from the searching.

10
2. Check if the left subtree's root has the value 10. The next left root value =
50. again 10 < 50. So we can skip the right subtree from the search as the
key value is less than the root.

1. Left subtree's root key value = 50. 10 < 50.


2. So we can skip the right subtree from the searching.
we can find the node with the value 10 in a minimal search count. That's
how the binary search tree effectively improves data manipulation.
NOTE:- In a normal array and linked list, there is no way we can skip
some elements from searching as they don't follow any data
arrangement rules like the binary search tree
11
Binary Search Tree - Node Structure:- BST Node structure is similar to a
Double Linked list

struct node
{
int key;
struct node *left;
struct node *right;
};
key - It can be any data type. char, float, double, string.
*left - Reference to the left node. It holds the memory address of the left chi
*right - Reference to the right node. It holds the memory address of the righ
child.
struct node
{
int key;
struct node *left;
struct node *right;
};
struct node *root;
root = malloc(sizeof(struct node)); // memory allocation
12
Assign values to the node
struct node
{
int key;
struct node * left;
struct node *right;
};
struct node *root;
root = malloc(sizeof(struct node)); // memory allocation
Root-> key=30;
Root-> left=NULL;
Root->right=NULL;

NULL 30 NULL

right
left Root (1120) address
location
13
Construct BST with following elements
19, 55,44,98,8,23,15,10,6,99,82

Root
19

8 55

6 15
44 98

10
23
82 99

14
BST Operations:- The following operations are performed on a binary search
tree...
1.Search
2.Insertion
3.Deletion

15
Insert Operation:- The insertion operation is performed with O(log
n) time complexity. A new node is always inserted as a leaf node.
The insertion operation is performed as follows...
i.Create a new Node with a given value and set
its left and right to NULL.
ii.Check whether the tree is Empty.
iii. If the tree is Empty, then set the root to newNode.
iv. If the tree is Not Empty, then check whether the value of the new
node is smaller or larger than the node
v. If newNode is smaller than the node then move to its left child. If
newNode is larger than the node then move to its right child.
vi. Repeat the above steps until we reach the leaf node (i.e., reach
NULL).
vii. After reaching the leaf node, insert the new node as the left child if
the new node is smalleri. orIf node equal== to NULL
that leaf node or else insert it
as the right child. ii. return createNode(data)
iii. if (data < node->data)
iv. node->left = insert(node->left, data);
v. else if (data > node->data)
vi. node->right = insert(node->right, data);
vii. return node;
16
Insert ELEMENT 4 TO FOLLOWING BST

4<8 so, transverse through the left child 4>3 so, transverse through the right c
of 8

4<6 so, transverse through the left child of 6 Insert 4 as a left child of 6

17
1) Search Operation:- A binary search tree, the search operation is
performed with O(log n) time complexity.
The search operation is performed as follows.
i.Read the search element from the user.
ii.Compare the search element with the value of root node in the tree.
iii.If both are matched, then display "Given node is found!!!" and terminate
the function
iv.If both are not matched, then check whether search element is smaller or
larger than that node value.
v.If search element is smaller, then continue the search process in left
subtree.
vi.If search element is larger, then continue the search process in right
subtree.
vii.Repeat the same until we find the exact element or until the search
element is compared with the leaf node
viii. If we reach to the node having the value equal to the search value then
display "Element is found" and terminate the function.
ix.If we reach to the leaf node and if it is also not matched with the search
element, then display "Element is not found" and terminate the function.

18
Search Algorithm:-
If root == NULL
return NULL;
If number == root->data
return root->data;
If number < root->data
return search(root->left)
If number > root->data
return search(root->right)
EG:- Assume 4 is a search element from the following BST

4 is not found so, traverse through the left subtree


of 8
19
4 is not found so, traverse through the right subtree
of 3

4 is not found so, traverse through the left subtree of 6


20
4 is found

21
 If the value is found, we return the value so that it gets propagated in
each recursion step as shown in the above fig.
 From the above search operation, we have called return search(struct
node*) four times.
 When we return either the new node or NULL, the value gets
returned again and again until the search(root) returns the final
result.
 If the value is not found, we eventually reach the left or right child of
a leaf node which is NULL and it gets propagated and returned.

22
Deletion Operation:-In a binary search tree, the deletion operation is
performed with O(log n) time complexity. Deleting a node from the
Binary search tree includes the following three cases

Case 1: Deleting a Leaf node (A node with no children)


Case 2: Deleting a node with one child
Case 3: Deleting a node with two children

Case 1: Deleting a Leaf node (A node with no children)


To Delete a leaf node from the BST we can delete it directly by
using flowing steps.
i.Find the node to be deleted using the search operation

ii. Delete the node using a free function (If it is a leaf) and terminate
the function.

23
Eg:- From the following BST to delete node 4.

i. First search where the node 4


by using the search operation.
ii. Identify node 4

Delete the node

24
Case 2: Deleting a node with one child
To delete a one-child node from BST the following steps are needed.

i.Find the node to be deleted using the search operation


ii.If it has only one child then create a link between its parent node and
child node.
iii. Delete the node using the free function and terminate the function.

Eg:- Delete node 6 from the following BST.

25
Step1:- search the node -6

Node -6 founded

Step2:- establish a link between the parent


node to Child node
Step3:- After linking tree

26
Case 3: Deleting a node with two children
To delete a node with two children from BST the following steps
are used.
i. Get the inorder successor of that node.
ii.Replace the node with the inorder successor.
iii.Remove the in-order successor from its original position.

3 is to be deleted

27
Copy the value of the inorder successor (4) to the node

28
7,23,15,32,65,12,55,45,99,18,23

29
Complexity

Algorithm Average case Worst case


Space o(n) o(n)
Search o(log n) o(log n)
Insert o(log n) o(log n)
Delete o(log n) o(log n)

30
Operations on an AVL Tree
The following operations are performed on the AVL tree
1.Search
2.Insertion
3.Deletion

Search Operation in AVL Tree:-

31
1)LL Rotation:- When BST becomes unbalanced, due to a node is
inserted into the left subtree of the left subtree of C, then we perform LL
rotation, LL rotation is clockwise rotation, which is applied on the edge
below a node having balance factor 2.

In above example, node A has balance factor -2 because a


node C is inserted in the right subtree of A right subtree. We
perform the RR rotation on the edge below A.

32
3. LR Rotation

Double rotations are bit tougher than single rotation which has
already explained above. LR rotation = RR rotation + LL rotation,
i.e., first RR rotation is performed on subtree and then LL rotation
is performed on full tree, by full tree we mean the first node from
the path of inserted node whose balance factor is other than -1, 0,
or 1.
State Action

33
AVL Tree:- AVL Tree is invented by GM Adelson - Velsky and EM Landis
in 1962. The tree is named AVL in honor of its inventors.
AVL Tree can be defined as a height-balanced binary search tree in
which each node is associated with a balance factor which is calculated
by subtracting the height of its right sub-tree from that of its left sub-
tree.
Tree is said to be balanced if the balance factor of each node is in
between -1 to 1, otherwise, the tree will be unbalanced and need to be
balanced.
Balance Factor (k) = height (left(k)) - height
(right(k))
 If the balance factor of any node is 1, it means that the left
sub-tree is one level higher than the right sub-tree.
 If the balance factor of any node is 0, it means that the left
sub-tree and right sub-tree contain equal height.
 If the balance factor of any node is -1, it means that the left
sub-tree is one level lower than the right sub-tree.

34
35
Operations on AVL tree:- AVL tree is a binary search tree So it
performs all the operations are performed in the same way as they
are performed in a binary search tree. But follow the properties of
AVL tree.

SN Operation Description
1 Insertion Insertion in the AVL tree is performed in the same
way as it is performed in a binary search tree. But,
it may lead to a violation in the AVL tree property
and so the tree may need balancing. The tree can
be balanced by applying rotations.
2 Deletion Deletion can also be performed in the same way as
it is performed in a binary search tree. Deletion
may also disturb the balance of the tree therefore,
various types of rotations are used to rebalance
the tree.

36
In the 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.
1.L L rotation: Inserted node is in the left subtree of left subtree of A
2.R R rotation : Inserted node is in the right subtree of right subtree of
A
3.L R rotation : Inserted node is in the right subtree of left subtree of A
4.R L rotation : Inserted node is in the left subtree of right subtree of A

37
Case 1: LEFT-LEFT insertion
• Unbalanced occurred due to the insertion in the left sub tree of
the left child of the pivot node.
• Steps to follow
1. Right sub- tree(AR) of left child(A) of pivot node (P) becomes the
left sub tree of P.
2. P becomes the right child of A.
3. Left sub- tree(AL) of A remains the same.

P A

P
A
AL
PR
AR
AR PR
AL
38
1 LL Rotation example
8 Insert 2 2
1 8
0 2
6 10 0
0 0 0 0 6 10
4 7 9 11 1 0 0
4 7 0 9 11
0
3 5 0
1 3 5
0
0
2

39
LL Rotation example
8

Pivot 6 10
A PR
4 7 9 11

3 5

2 AL AR

40
LL Rotation example
8 1

0 0
4 10
0 0 0
1 9 11
3 6
0
0
0 5 7
2

41
Case-2 RIGHT- RIGHT insertion
 Unbalance due to insertion in the right sub tree of right
child of pivot node.
The following manipulations takes place
1. Left sub tree (BL) of right child(B) of pivot node (P) becomes
the right sub- tree of P.
2. P become the left child of B.
3. Right sub tree (BR) of B remains same.
B
P

P
B
PL
BL BR
PL
BL
BR
After insertion

42
RR insertion
example
7 -1 Pivot
-2 Insert - 12
0
5 9 -1 -2
0 B
0
0 11 0 -1
4 6 8

PL 0
0 10 13

12 BR
BL

43
After rotations
-1
7

0 0 B
11
5
1
13
0 0 6 0
4 9
12
8
10 BR
0
0

44
Case-3 Left to Right insertion
• Unbalanced due to insertion in the right sub tree of right child
of pivot node.
• Involves two rotations
Rotation-1
- left sub tree (BL) of the right child (B) of the left child of pivot
node(P) becomes the right sub tree of the left child(A).
- Left child (A) of the pivot node (P) becomes the left child of B.
Rotation- 2
- Right sub tree (BR) of right child(B) of the left child (A) of the
pivot node (P) becomes the left sub tree of P.
- P becomes the right child of B

45
LEFT RIGHT insertion

P B

2
A A P
PR

AL B
AL
BL BR PR

BR
BL

Balanced tree
Unbalanced tree

46
LEFT-RIGHT insertion Example
1 8 -2
8
0 -1 0
0
10 3 10
3

1 0 1 -1 0 0
0 0
2 5 9 11 2 5 9 11

0 0 0 0 -1
0
1 6 1 4 6
4
0
Height Balanced Tree
7

Un balanced due to insertion of 7

47
Pivot node

8 -2
A
-1 0

3 10 PR

1 -1 0 0
2 5 9 11
B
0 0 -1
1 4 6

AL 0

7
BL BR

48
5

3 8

2 4 10
6
0 BL
1
9 11
AL 7

PR
BR

49
Case-4 Right to left insertion
• Unbalanced occurred due to the insertion in the right sub tree of the left child of the pivot
node.
• Two rotations takes place
rotation -1
 Right sub tree(BR) of the left child (B) of the right child(A) of the pivot node (P) becomes the
left sub tree of A.
 Right child (A) of the pivot node(P) becomes the right child of B.

P B

A After first rotation


2 A
PL
1
B AR

AR
BL
BR BR
50
Rotation-2
 Left sub-tree(BL)of the right child(B) of the right child(A) of the
pivot node(P) becomes the right sub-tree of P.
 P becomes the left child of B

B
P
After two rotations A
A P
PL 2
1
B AR AR
PL BL
BR
BL
BR

51
Right to left rotation example
7 -1

0 -1
5 9

0
12 1
8
0 0
4 6
0
0 11 13

52
Right to left rotation example
Insert-10
7 -1-2
P

0 -1
5 PL 9 -2
A
0
12 1
8
0 01
4 6
B 0
0 11 13

AR

10
BR
BL
53
Right to left rotation example
After AVL rotations
-1
7
0

5 0
11

0 0 0
4 6 9 -1
12
0 0
0
8 10
13
PL BL BR

AR

54
AVL Tree Example:
• Insert 14, 17, 11, 7, 53, 4, 13 into an empty AVL tree

14

11 17

7 53

55
AVL Tree Example:
• Insert 14, 17, 11, 7, 53, 4, 13 into an empty AVL tree

14

7 17

4 11 53

13

56
AVL Tree Example:
• Now insert 12

14

7 17

4 11 53

13

12

57
AVL Tree Example:
• Now insert 12

14

7 17

4 11 53

12

13

58
AVL Tree Example:
• Now the AVL tree is balanced.

14

7 17

4 12 53

11 13

59
AVL Tree Example:
• Now insert 8

14

7 17

4 12 53

11 13

60
AVL Tree Example:
• Now insert 8

14

7 17

4 11 53

8 12

13

61
AVL Tree Example:
• Now the AVL tree is balanced.

14

11 17

7 12 53

4 8 13

62
AVL Tree Example:
• Now remove 53

14

11 17

7 12 53

4 8 13

63
AVL Tree Example:
• Now remove 53, unbalanced

14

11 17

7 12

4 8 13

64
AVL Tree Example:
• Balanced! Remove 11

11

7 14

4 8 12 17

13

65
AVL Tree Example:
• Remove 11, replace it with the largest in its left branch

7 14

4 12 17

13

66
AVL Tree Example:
• Remove 8, unbalanced

4 14

12 17

13

67
AVL Tree Example:
• Remove 8, unbalanced

4 12

14

13 17

68
AVL Tree Example:
• Balanced!!

12

7 14

4 13 17

69
In Class Exercises
• Build an AVL tree with the following values:
15, 20, 24, 10, 13, 7, 30, 36, 25

70
15, 20, 24, 10, 13, 7, 30, 36, 25
20

15
15 24
20
10
24

13

20 20

13 24 15 24

10 15 13

10
71
15, 20, 24, 10, 13, 7, 30, 36, 25

20
13

13 24 10 20

10 15 7 15 24

7 30

36

13

10 20

7 15 30

24 36
72
15, 20, 24, 10, 13, 7, 30, 36, 25

13 13

10 20 10 20

7 15 30 7 15 24

24 36 30

25 13 25 36

10 24

7 20 30

15 25 36

73
Remove 24 and 20 from the AVL tree.

13 13

10 24 10 20

7 20 30 7 15 30

15 25 36 25 36

13 13

10 30 10 15

7 15 36 7 30

25 25 36 74
B-Trees:-
In the search tree like binary search tree, AVL Tree, Red-
Black tree, etc., every node contains only one value (key) and a
maximum of two children. But there is a special type of search
tree called B-Tree in which a node contains more than one value
(key) and more than two children. B-Tree was developed in the
year 1972 by Bayer and McCreight with the name Height
Balanced m-way Search Tree. Later it was named as B-Tree.
“B-Tree is a self-balanced search tree in which every node
contains multiple keys and has more than two children.”

The number of keys in a node and the number of children for a


node depends on the order of the B-Tree. Every B-Tree has an
order.
B Tree is a specialized m-way tree that can be widely used for disk
access. A B-Tree of order m can have at most m-1 keys and m
children. One of the main reasons for using the B tree is its
capability to store a large number of keys in a single node 75 and
large key values by keeping the height of the tree relatively small.
Property of B Tree:- A B Tree of order m can be defined as
an m-way search tree that is either empty or full and it satisfies
the following properties:
i.All leaf nodes of a B tree are at the same level, i.e. they have
the same depth (height of the tree).
ii.The keys of each node of a B tree (in case of multiple keys),
should be stored in ascending order.
iii.All non-leaf nodes (except the root node) should have at
least m/2 children.
iv.All nodes (except the root node) should have at least m/2 -
1 keys.
v.If the root node is a leaf node (the only node in the tree), then it
will have no children and will have at least one key. If the root
node is a non-leaf node, then it will have at least 2 children and
at least one key.
vi.A non-leaf node with n-1 key values should have n non-NULL
76
children.
77
Operations on a B Tree:-The following operations are performed on a B-
Tree...
i.Search ii. Insertion iii. Deletion

i)Searching Operation on B Tree:- Searching in a B Tree is


similar to that in a Binary Search Tree. In a BTree instead of
making a 2-way decision (left or right), makes an n-way decision at
each node where n is the number of children of the node
Steps to search an element in B Tree :-The search starts from
the root node. Compare the search element k with the root.
1.1 If the root node value is equal to search element (k) then the search
completes.
1.2. If k < the first value in the root, we move to the leftmost child and
search the child recursively.
1.3.1. If the root has just 2 children, then move to the rightmost child and
search for the child recursively.
1.3.2. If the root has more than 2 keys, then search the rest.
If k is not found after traversing the whole tree, then the search element is
not present in the B Tree. 78
Algorithm for Searching an Element

i. BtreeSearch(x, k)
ii. i = 1
iii. while i ≤ n[x] and k ≥ keyi[x] // n[x]
means number of keys in x node
iv. do i = i + 1
v. if i n[x] and k = keyi[x]
vi. then return (x, i)
vii. if leaf [x]
viii. then return NIL
ix. else
x. return BtreeSearch(ci[x], k)

79
80
Inserting Operation on B Tree

While inserting an element into the B tree, we have to first


check whether the element is already present in the tree. If the
element is found, then the insertion doesn't take place. If not, we will
proceed further with the insertion.
2 cases need to be taken care of while inserting the key in the leaf
node:

1.Node does not contain more than MAX number of keys - Simply
insert the key in the node at its proper place.

2.A node contains MAX number of keys – A key is inserted into the full
node and then a split takes place splitting the full node into 3 parts.
The second or median key moves to the parent node and the first and
third parts act as the left and right children. The process is repeated
with the parent node if it contains MAX number of keys too.

81
Steps to insert an element in B Tree
1.Calculate the maximum number of keys in the node based on the order of the B
tree.
2.If the tree is empty, a root node is allocated and the key is inserted and acts as the
root node.
3.Search the appropriate node for insertion.`
4.If the node is full:
4.1. Insert the elements in increasing order.
4.2. If the elements are greater than the maximum number of keys, split at
the median.
4.3. Push the median key upwards and split the left and right keys as left and
right child respectively.
5.If the node is not full, insert the node in increasing order.

Suppose we have to create a B tree of order 4.


The elements to be inserted are 4, 2, 20, 10, 1, 14, 7, 11, 3, 8.
Since m=3, max number of keys for a node = m-1 = 2. ,min(m/2-1=4/2-1=1)
1.Insert 4
2.Since 2<4, insert 2 to the left of 4 in the same node.
3.Since 20>4, insert 20 to the right of 4 in the same node. now, the maximum
number of keys in the node is 2, one of these keys will have to be moved to a node
above to split it. 4 is the middle element that will move up and 2 and 20 will be its left
and right nodes respectively.
4.10>4 and 10<20 and thus, 10 will be inserted as a key in the node that contains 20
as a key. 82
5. Since 1<2, it will be inserted as a key in the node that contains 2 as a
key.
6. 14>10 and 14<20. Since the number of keys in that node exceeds the
maximum number of keys, the node will split after the middle key
moves upto the node in the above line. Thus, 14 gets added to the right
of 4 in the node that contains 4, and 10 and 20 are split as 2 separate
nodes.
7. Since 7<10, it gets inserted to the left in the node that contains 10 as a
key.
8. 11<14 and 11>10. Thus, 11 should get added to the right of the node
that contains 7 and 10. However, since the maximum number of keys in
the tree are 2, a split should take place. Thus, the middle
element 10 moves to the above node, and 7 and 11 splits as separate
nodes. The above node now contains 4, 10 and 14. Since the count of
keys exceeds the maximum key count, there would be a split there.
Now, 10 is the root node with 4 and 14 as its children.
9. Since 3<4 and 3>2,it gets inserted to the right of the node
containing 1, 2. This node exceeds the maximum count of keys in a
node, leading to a split. 2 is added to the upper node beside 4.
10.Since 8>7 and 8<10, it gets added to the left of the node that
contains 7 as a key.
The number of comparisons at each step varied. The first value was
directly entered, thereafter every value had to be compared with83the
nodes present in the tree. The time complexity for insertion in a B Tree
Algorithm for Inserting an Element

84
85
86
87
Deletion Operation on B Tree
Deletion of a key in a B tree includes two cases
i.Deletion of key from a leaf node
ii.Deletion of a key from an Internal node

we want to delete the key 64 and the node in which 64 is present, has
more than minimum number of nodes required by the B tree, which is
2. So, we can simply delete this node.

88
89
Case 1 - Deletion from Leaf Node
1.1. If the node has more than MIN keys - Deletion of key does not
violate any property and thus the key can be deleted easily by shifting
other keys of the node, if required.
1.2. If the node has less than MIN keys - This kind of deletion
violates a property of B tree. In case the keys in the left sibling are
greater than MIN, keys are borrowed from there. If the keys in right
sibling are greater than MIN, then keys are borrowed from there. If either
of these do not hold true, then a combination of node takes place with
either of the siblings.
Case 2 - Deletion from Non-Leaf Node
In this case, the successor key (smallest key in the right subtree) is
copied at the place of the key to be deleted and then the successor is
deleted. This case further reduces to Case 1, i.e. deletion from a leaf
node.

90
From the B tree of order 4 with the nodes 5, 12, 32, and 53 to
be deleted in the given order.

Since the order of the B tree is 4, the minimum and maximum number of
keys in a node are 2 and 4 respectively.

91
Step 1 - Deleting 5
Since 5 is a key in a leaf node with keys>MIN, this would be Case 1.1.
A simple deletion with a key shift would be done. Keys 9 and 10 are
shifted left to fill the gap created by the deletion of 5.

92
Step 2 - Deleting 12 :- key 12 is to be deleted from node [12,17]. Since
this node has only MIN keys, we will try to borrow from its left sibling
[2,9,10] which has more than MIN keys. The parent of these nodes [11,21]
contains the separator key 11. So, the last key of left sibling (10) is moved
to the place of the separator key and the separator key is moved to the
underflow node (the node where deletion took place). The resulting tree
after deletion can be found as follows:

93
Step 3 - Deleting 32: key 32 is to be deleted from node [32, 41]. Since
this node has only MIN keys and does not have a left sibling, we will try to
borrow from its right sibling [53, 61, 64] which has more than MIN keys.
The parent of these nodes [51, 67] contains the separator key 51. So, the
first key of right sibling (53) is moved to the place of the separator key and
the separator key is moved to the underflow node (the node where deletion
took place). The resulting tree after deletion can be found as follows:

94
Step 4 - Deleting 53:- key 53 is to be deleted from node [53, 67] which is
a non-leaf node. In such a case, the successor key (61) will be copied in
place of 53 and now the task reduces to the deletion of 61 from the leaf
node. Since this node would have less than MIN keys, we check for the left
sibling. Since the left sibling has only MIN keys, we move to the right sibling.
The leftmost key of the right sibling (68) moves to the parent node and
replaces the separator (67) while the separator shifts to the underflow node
making it [64,67]. The resulting tree after deletion can be found as follows:

95
Note:- The time complexity here varies depending on the location from
where the key has to be deleted. The average time complexity required
for the deletion operation in a B Tree is thus O(log n).
Application of B Tree
1.Database or File System - Consider having to search details of a
person in Yellow Pages (directory containing details of professionals).
Such a system where you need to search a record among millions can
be done using B Tree.
2.Search Engines and Multilevel Indexing - B tree Searching is
used in search engines and also querying in MySql Server.
3.To store blocks of data - B Tree helps in faster storing blocks of
data in secondary storage due to the balanced structure of B Tree.
Key Points:
•The time complexity for search, insert and delete operations in
a B tree is O(log n).
•The minimum number of keys in a B tree should be [M/2] - 1.
•The maximum number of keys in a B tree should be M-1.
•All the leaf nodes in a B tree should be at the same level.
•All the keys in a node in a binary tree are in increasing order.
•B Trees are used in SQL to improve the efficiency of queries.
•Each node in a B Tree can have at most M children.

96
HOMEWORK:-
Create a B tree of order 5 by inserting the following elements:
1)3, 14, 7, 1, 8, 5, 11, 17, 13, 6, 23, 12, 20, 26, 4, 16, 18, 24, 25, and 19

2)1, 12, 8, 2, 25, 6, 14, 28, 17, 7, 52, 16, 48, 68, 3, 26, 29, 53, 55, 45
3)Insert the following into 5- way b- tree
3, 7, 9, 23, 45, 1, 5, 14, 25, 24, 13, 11, 8, 19, 4, 31, 35, 56
Add these further keys: 2, 6 and 12.
Delete these keys : 4, 5, 7, 3, 14

4) Create a B-tree of order-5


AGFBKDHMJESIRXCLNTUP
.

97
Red - Black Tree Data structure:- Red - Black Tree is another variant
of Binary Search Tree in which every node is colored either RED or BLACK
Red Black Tree is a Binary Search Tree in which every node is
colored either RED or BLACK.
In Red Black Tree, the color of a node is decided based on the properties
of Red-Black Tree. Every Red Black Tree has the following properties.

Properties of Red Black Tree:-

Property #1: Red-Black Tree must be a Binary Search Tree.


Property #2: The ROOT node must be colored BLACK.
Property #3: The children of the Red-colored node must be colored
BLACK. (There should not be two consecutive RED nodes).
Property #4: In all the paths of the tree, there should be the same
number of BLACK-colored nodes.
Property #5: Every new node must be inserted with RED color.
Property #6: Every leaf (e.i. NULL node) must be colored BLACK.

98
Every Red Black Tree is a binary search tree but every Binary Search
Tree need not be a Red-Black tree

https://www.programiz.com/dsa/insertion-in-a-red-black-tree

99
Insertion into RED BLACK Tree:- In a Red-Black Tree, every new node
must be inserted with the color RED. The insertion operation in Red
Black Tree is similar to the insertion operation in Binary Search Tree. But
it is inserted with a color property. After every insertion operation, we
need to check all the properties of the Red-Black Tree. If all the
properties are satisfied then we go to the next operation otherwise we
perform the following operation to make it Red Black Tree.
•1. Recolor 2. Rotation 3. Rotation followed by
Recolor
The insertion operation in Red Black tree
Step 1 - Check whether the tree is Empty.
Step 2 - If tree is Empty then insert the newNode as Root node with
color Black and exit from the operation.
Step 3 - If tree is not Empty then insert the newNode as leaf node with
color Red.
Step 4 - If the parent of newNode is Black then exit from the operation.
Step 5 - If the parent of newNode is Red then check the color of
parentnode's sibling of newNode.
Step 6 - If it is colored Black or NULL then make suitable Rotation and
Recolor it.
Step 7 - If it is colored Red then perform Recolor. Repeat the same until
tree becomes Red Black Tree.

100
Example

101
102
103
104
105
106
107
Deletion Operation in Red Black Tree:- The deletion operation in Red-
Black Tree is similar to the deletion operation in BST. But after every
deletion operation, we need to check with the Red-Black Tree properties. If
any of the properties are violated then make suitable operations like
Recolor, Rotation and Rotation followed by Recolor to make it Red-Black
Tree

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

109
https://www.programiz.com/dsa/binary-search-tree

110

You might also like