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

Module 4 Trees

Uploaded by

sungjinwooho
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Module 4 Trees

Uploaded by

sungjinwooho
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 265

UNIT - IV

TREES
DATA STRUCTURE HIMANI DESHPANDE ( TSEC ) 1
Introduction

Tree Terminologies

Binary Tree and Types of Binary Tree, Binary


Tree Traversals
CONTENT Binary Search Tree, Operations on Binary Search
Tree
Applications of Binary Tree-Expression Tree,
Huffman Encoding
AVL Tree & operations on AVL Tree

Introduction of B-Tree & B+ Tree


HIMANI DESHPANDE ( TSEC ) 2
HIMANI DESHPANDE ( TSEC ) 3
Non

HIMANI DESHPANDE ( TSEC ) 4


TREES
oTree is a non-linear data structure which organizes data in a hierarchical structure.
oIt consists of nodes with parent-child relationship.

HIMANI DESHPANDE ( TSEC ) 5


PROPERTIES OF TREES

oThere is one and only one path between every pair of vertices in a
tree.
oA tree with n vertices has exactly (n-1) edges.
oA graph is a tree if and only if it is minimally connected.
oAny connected graph with n vertices and (n-1) edges is a tree.

HIMANI DESHPANDE ( TSEC ) 6


TREE TERMINOLOGY
HIMANI DESHPANDE ( TSEC ) 7
ROOT
oThe first node from where the tree
originates is called as a root node.
oIn any tree, there must be only one
root node.
oWe can never have multiple root
nodes in a tree data structure.

HIMANI DESHPANDE ( TSEC ) 8


EDGE
oThe connecting link between any two
nodes is called as an edge.
oIn a tree with n number of nodes,
there are exactly (n-1) number of
edges.

HIMANI DESHPANDE ( TSEC ) 9


PARENT
oThe node which has a branch from it
to any other node is called as a
parent node.
oIn other words, the node which has
one or more children is called as a
parent node.
oIn a tree, a parent node can have
any number of child nodes.

HIMANI DESHPANDE ( TSEC ) 10


CHILD
oThe node which is a descendant of
some node is called as a child node.
oAll the nodes except root node are
child nodes.

HIMANI DESHPANDE ( TSEC ) 11


SIBLINGS
oNodes which belong to the same
parent are called as siblings.
oIn other words, nodes with the same
parent are sibling nodes.

HIMANI DESHPANDE ( TSEC ) 12


DEGREE
oDegree of a node is the total number of
children of that node.
oDegree of a tree is the highest degree of a
node among all the nodes in the tree.

Degree of
node A = 2, node F = 0,
node B = 3, node G = 1,
node C = 2, node H = 0,
node D = 0, node I = 0,
node E = 2. node J = 0,
node K = 0 HIMANI DESHPANDE ( TSEC ) 13
INTERNAL NODE
oThe node which has at least one child
is called as an internal node.
oInternal nodes are also called as
non-terminal nodes.
oEvery non-leaf node is an internal
node.

nodes A, B, C, E and G are internal nodes

HIMANI DESHPANDE ( TSEC ) 14


LEAF NODE

oThe node which does not have


any child is called as a leaf node.
oLeaf nodes are also called as
external nodes or terminal nodes.

HIMANI DESHPANDE ( TSEC ) 15


LEVEL
oIn a tree, each step from top to
bottom is called as level of a tree.
oThe level count starts with 0 and
increments by 1 at each level or step.

HIMANI DESHPANDE ( TSEC ) 16


HEIGHT OF A NODE & TREE
oTotal number of edges that lies on
the longest path from any leaf node
to a particular node is called as
height of that node.
oHeight of a tree is the height of root
node.
oHeight of all leaf nodes = 0

Height of node A = , node B = , node C = ,


node D =, node E = , node F = ,
node G = , node H = , node I = ,
node J = , node K =
HIMANI DESHPANDE ( TSEC ) 17
HEIGHT OF A NODE & TREE
oTotal number of edges that lies on
the longest path from any leaf node
to a particular node is called as
height of that node.
oHeight of a tree is the height of root
node.
oHeight of all leaf nodes = 0

Height of node A = 3, node B = 2, node C = 2,


node D = 0, node E = 1, node F = 0,
node G =1 , node H = 0, node I = 0,
node J = 0, node K = 0
HIMANI DESHPANDE ( TSEC ) 18
DEPTH
oTotal number of edges from root node
to a particular node is called as depth
of that node.
oDepth of a tree is the total number of
edges from root node to a leaf node in
the longest path.
oDepth of the root node = 0
oThe terms “level” and “depth” are used
interchangeably.

HIMANI DESHPANDE ( TSEC ) 19


SUBTREE
oIn a tree, each child from a node
forms a subtree recursively.
oEvery child node forms a subtree
on its parent node.

HIMANI DESHPANDE ( TSEC ) 20


FOREST

oA forest is a set of
disjoint trees.

HIMANI DESHPANDE ( TSEC ) 21


ANCESTOR & DESCENDENT

HIMANI DESHPANDE ( TSEC ) 22


BINARY TREE
HIMANI DESHPANDE ( TSEC ) 23
BINARY TREE
The Binary tree means that the node can have maximum two children.
Here, binary name itself suggests that 'two'; therefore, each node can have either 0, 1 or 2 children.

struct node
{
struct node *left ;
int data ;
struct node *right ;
}

HIMANI DESHPANDE ( TSEC ) 24


HIMANI DESHPANDE ( TSEC ) 25
PROPERTY-01
Minimum number of nodes in a
binary tree of height H
=H+1

Example:
To construct a binary tree of height =
4, we need at least 4 + 1 = 5 nodes.

HIMANI DESHPANDE ( TSEC ) 26


PROPERTY-02
Maximum number of nodes in a
binary tree of height H
= 2𝐻+1 -1

Example:
Maximum number of nodes in a binary tree of
height 3
= 23+1 – 1
= 16 – 1
= 15 nodes

HIMANI DESHPANDE ( TSEC ) 27


PROPERTY-03
Maximum number of nodes at any
level ‘L’ in a binary tree
= 2L

Example:
Maximum number of nodes at level-2
in a binary tree
= 22
=4

HIMANI DESHPANDE ( TSEC ) 28


PROPERTY-04
Total Number of leaf nodes in a Binary Tree
= Total Number of nodes with 2 children + 1

Here,

Number of nodes with 2 children = 2


Number of leaf nodes = 2+1 = 3

HIMANI DESHPANDE ( TSEC ) 29


HIMANI DESHPANDE ( TSEC ) 30
STRICT BINARY TREE
oIt is a binary Tree in which every
node has 0 or 2 children.
oIt is also called as proper binary
tree.

oFor Full Binary Tree, following


equation is always true.
Number of Leaf nodes =
Number of Internal nodes + 1 Valid strict Invalid strict
binary tree binary tree

HIMANI DESHPANDE ( TSEC ) 31


COMPLETE BINARY
TREE

oAll levels completely filled with


nodes except the last level and in
the last level, all the nodes are as
left side as possible. Valid complete Invalid complete
binary tree binary tree

HIMANI DESHPANDE ( TSEC ) 32


PERFECT BINARY TREE
oIt is a Binary Tree in which all

internal nodes have 2 children, and

all the leaf nodes are at the same

depth or same level.

oTotal number of nodes in a Perfect Valid perfect Invalid perfect


binary tree binary tree
Binary Tree with height H is 2^H - 1.

HIMANI DESHPANDE ( TSEC ) 33


BALANCED BINARY
TREE
oIt is a Binary tree in which
height of the left and the right sub-trees
of every node may differ by at most 1.
oDiff=
|ht. of left subtree - ht. of right subtree|
oAVL Tree is well-known data structure to
generate/maintain Balanced Binary Search
Tree.
Valid balanced Invalid perfect
binary tree binary tree

HIMANI DESHPANDE ( TSEC ) 34


HIMANI DESHPANDE ( TSEC ) 35
REPRESENTATION OF BINARY TREE
There are two different methods for representing:
a) using array

oThe index 1 is holding the root, it has two children 5 and 16, they are placed at
location 2 and 3.
left

Right
HIMANI DESHPANDE ( TSEC ) 36
REPRESENTATION OF BINARY TREE

oSome children are missing, so their place in array is left as blank.


oThis approach is good, and easily we can find the index of parent and child, but it is
not memory efficient.
oIt will occupy many spaces that has no use.
oThis representation is good for complete binary tree or full binary tree.

HIMANI DESHPANDE ( TSEC ) 37


REPRESENTATION OF BINARY TREE
b) using linked list

HIMANI DESHPANDE ( TSEC ) 38


HIMANI DESHPANDE ( TSEC ) 39
BINARY TREE TRAVERSAL
oTraversal is a process to visit all the nodes of a tree and may print their values too.
Because, all nodes are connected via edges (links) we always start from the root
(head) node.
oIn tree, relative order of traversing left subtree, right subtree & visiting root can be
different.
oTypes of traversals:
1. Preorder – VLR <visit root> <left subtree> <right subtree>
2. Inorder – LVR <left subtree> <visit root> <right subtree>
3. Postorder – LRV <left subtree> <right subtree> <visit root>

HIMANI DESHPANDE ( TSEC ) 40


PREORDER TRAVERSAL
In this traversal method, the root node is visited
first, then the left subtree and finally the right
subtree.
Algorithm:
Until all nodes are traversed −
Step 1 − Visit root node.
Step 2 − Recursively traverse left subtree.
Step 3 − Recursively traverse right subtree.

HIMANI DESHPANDE ( TSEC ) 41


PREORDER TRAVERSAL

O/P:
A→B→D→E→C→F→G

HIMANI DESHPANDE ( TSEC ) 42


PREORDER TRAVERSAL

Code snippet

void preorder(struct node *root)


{
if(root==null)
return;
printf(“%c”,root -> data);
preorder(root -> left);
O/P:
preorder(root -> right); {30 , 20 , 15 , 5 , 18 , 25 , 40 , 35 , 50 , 45 , 60}
}
HIMANI DESHPANDE ( TSEC ) 43
After the completion of preorder traversal, the final output is -
40, 30, 25, 15, 28, 35, 50, 45, 60, 55, 70

PREORDER

HIMANI DESHPANDE ( TSEC ) 44


PREORDER TRAVERSAL

O/P:
ABDCEGFHI

HIMANI DESHPANDE ( TSEC ) 45


INORDER TRAVERSAL
In this traversal method, the left subtree is visited
first, then the root and later the right sub-tree.
Algorithm:
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Visit root node.
Step 3 − Recursively traverse right subtree.

HIMANI DESHPANDE ( TSEC ) 46


INORDER TRAVERSAL

O/P:
D→B→E→A→F→C→G

HIMANI DESHPANDE ( TSEC ) 47


After the completion of inorder traversal, the final output is -
{15, 25, 28, 30, 35, 40, 45, 50, 55, 60, 70}

INORDER TRAVERSAL

HIMANI DESHPANDE ( TSEC ) 48


https://www.javatpoint.com/inorder-traversal
INORDER TRAVERSAL

O/P:
BDAGECHFI

HIMANI DESHPANDE ( TSEC ) 49


INORDER TRAVERSAL

O/P:
{5 , 15 , 18 , 20 , 25 , 30 , 35 , 40 , 45 , 50 , 60}

HIMANI DESHPANDE ( TSEC ) 50


INORDER TRAVERSAL

void inorder(struct node *root)


{Code snippet
if(root==null)
return;
inorder(root -> left);
printf(“%c”,root -> data);
inorder(root -> right);
} O/P:
{5 , 15 , 18 , 20 , 25 , 30 , 35 , 40 , 45 , 50 , 60}

HIMANI DESHPANDE ( TSEC ) 51


POSTORDER TRAVERSAL
In this traversal method, the root node is visited
last, hence the name. First, we traverse the left
subtree, then the right subtree and finally the
root node.
Algorithm:
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Recursively traverse right subtree.
Step 3 − Visit root node.

HIMANI DESHPANDE ( TSEC ) 52


POSTORDER TRAVERSAL

O/P:
D→E→B→F→G→C→A

HIMANI DESHPANDE ( TSEC ) 53


POSTORDER TRAVERSAL

Code snippet
void postorder(struct node *root)
{
if(root==null)
return;
postorder(root -> left);
postorder(root -> right);
printf(“%c”,root -> data); O/P:
{5 , 18 , 15 , 25 , 20 , 35 , 45 , 60 , 50 , 40 , 30}
}

HIMANI DESHPANDE ( TSEC ) 54


POSTORDER TRAVERSAL

O/P:
DBGEHIFCA

HIMANI DESHPANDE ( TSEC ) 55


void preorder(struct node *root)
{
if(root==null)
TRAVERSALS return;
printf(“%c”,root -> data); Root Left Right
preorder(root -> left);
preorder(root -> right);
}

void postorder(struct node *root)


void inorder(struct node *root) {
{ if(root==null)
if(root==null) return;
return; postorder(root -> left);
inorder(root -> left); postorder(root -> right);
printf(“%c”,root -> data); printf(“%c”,root -> data);
inorder(root -> right); }
}
Left Root Right Left Right Root
HIMANI DESHPANDE ( TSEC ) 56
EXAMPLE
Preorder Traversal-
100 , 20 , 10 , 30 , 200 , 150 , 300

Inorder Traversal-
10 , 20 , 30 , 100 , 150 , 200 , 300

Postorder Traversal-
10 , 30 , 20 , 150 , 300 , 200 , 100

HIMANI DESHPANDE ( TSEC ) 57


EXAMPLE
Preorder Traversal-
52, 40, 24, 32, 62, 58, 69

Inorder Traversal-
24, 32, 40, 52, 58, 62, 69

Postorder Traversal-
32, 24, 40, 58, 69, 62, 52

HIMANI DESHPANDE ( TSEC ) 58


EXAMPLE ROOT

Preorder Traversal-

Inorder Traversal-

Postorder Traversal-

HIMANI DESHPANDE ( TSEC ) 59


CONSTRUCTING BINARY TREE FROM TRAVERSAL
RESULTS
oWe can construct a binary tree if we are given
atleast two traversal results → (one should be in-order)
oIn pre-order, root is always displayed first.
oIn post-order, root is always displayed last.
oIn in-order, root is always displayed between left & right subtree.

oApplying this logic recursively we can form a tree

HIMANI DESHPANDE ( TSEC ) 60


EXAMPLE
In-oder: DBEAFCG
Pre-order: ABDECFG

HIMANI DESHPANDE ( TSEC ) 61


EXAMPLE
In-oder: DBEAFCG
Pre-order: ABDECFG

HIMANI DESHPANDE ( TSEC ) 62


EXAMPLE
In-oder: DBHEIAFJCG
Post-order: DHIEBJFGCA

HIMANI DESHPANDE ( TSEC ) 63


EXAMPLE
In-oder: DBHIEAFJCG
Post-order: DHIEBJFGCA

HIMANI DESHPANDE ( TSEC ) 64


HIMANI DESHPANDE ( TSEC ) 65
BINARY SEARCH TREE
oBinary Search Tree is a special kind of binary tree in which nodes
are arranged in a specific order.
oIn a binary search tree (BST), each node contains-
oOnly smaller values in its left sub tree
oOnly larger values in its right sub tree

HIMANI DESHPANDE ( TSEC ) 66


EXAMPLE

HIMANI DESHPANDE ( TSEC ) 67


CONSTRUCTING BINARY SEARCH TREE
data elements are -
45, 15, 79, 90, 10, 55, 12, 20, 50

HIMANI DESHPANDE ( TSEC ) 68


CONSTRUCTING BINARY SEARCH TREE
Construct a Binary Search Tree (BST) for the following sequence of numbers-
50, 70, 60, 20, 90, 10, 40, 100

HIMANI DESHPANDE ( TSEC ) 69


CONSTRUCTING BINARY SEARCH TREE
Construct a Binary Search Tree (BST) for the following sequence of numbers-
50, 70, 60, 20, 90, 10, 40, 100

HIMANI DESHPANDE ( TSEC ) 70


IMPORTANT NOTE
oIn-order traversal of a binary search tree always yields all the nodes in
increasing order

In-order Traversal
10 , 20 , 30 , 100 , 150 , 200 , 300

HIMANI DESHPANDE ( TSEC ) 71


PROBLEM ON BST
The pre-order traversal sequence of a binary search tree is-
30 , 20 , 10 , 15 , 25 , 23 , 39 , 35 , 42

What will be the post-order traversal sequence of the same tree?

HIMANI DESHPANDE ( TSEC ) 72


SOLUTION
30 , 20 , 10 , 15 , 25 , 23 , 39 , 35 , 42

HIMANI DESHPANDE ( TSEC ) 73


HIMANI DESHPANDE ( TSEC ) 74
CREATE TREE

void create_tree(struct node *root)


{
root = NULL;
}

HIMANI DESHPANDE ( TSEC ) 75


INSERTION

HIMANI DESHPANDE ( TSEC ) 76


Item to be inserted is 95
INSERTION

HIMANI DESHPANDE ( TSEC ) 77


INSERTION
Item to be inserted is 15

15

HIMANI DESHPANDE ( TSEC ) 78


INSERTION

HIMANI DESHPANDE ( TSEC ) 79


INSERTION

HIMANI DESHPANDE ( TSEC ) 80


INSERTION
while(nodeptr != null)
struct node *insertElement( struct node *root,
{
int val ) parentptr = nodeptr;
{ if( val < nodeptr -> data)
struct node *ptr, *nodeptr, *parentptr; nodeptr = nodeptr -> left;
ptr=(struct node*) malloc(sizeof(struct node)); else
ptr -> data = val; nodeptr = nodeptr -> right;
ptr -> left = null; }
ptr -> right = null; if(val < parentptr -> data)
if(root == null) parentptr -> left = ptr;
root = ptr; else
parentptr -> right = ptr;
else
}
{ return root;
parentptr = null; }
nodeptr = root;
HIMANI DESHPANDE ( TSEC ) 81
SEARCHING

HIMANI DESHPANDE ( TSEC ) 83


SEARCHING
60

HIMANI DESHPANDE ( TSEC ) 84


SEARCHING
struct node *BSTSearch(struct node *root, int key)
{
if(root==null)
return null;
else if(key == root -> data)
return root;
else if(key < root -> data)
return BSTSearch(root -> left, key);
else
return BSTSearch(root -> right, key);
}

HIMANI DESHPANDE ( TSEC ) 85


SEARCHING
struct node *BSTSearch(struct node *temp, int key)
{
if(temp==null)
return null;
else if(key == temp -> data)
return temp;
else if(key < temp -> data)
return BSTSearch(temp -> left, key);
else
return BSTSearch(temp -> right, key);
}
HIMANI DESHPANDE ( TSEC ) 86
DELETION
OF NODE

HIMANI DESHPANDE ( TSEC ) 87


DELETION
oDelete function is used to delete the specified node from a binary search tree.
oWe must delete a node from a binary search tree in such a way, that the property
of binary search tree doesn't violate.

There are three cases of deleting a node from binary search tree:

→ Case 1: A node has no child


→Case 2: A node has one child (either left or right)
→ Case 3: A node has two children
HIMANI DESHPANDE ( TSEC ) 88
CASE 1: A NODE HAS NO CHILD
Just remove / disconnect the leaf node that is to deleted from the tree

HIMANI DESHPANDE ( TSEC ) 89


CASE 1: A NODE HAS NO CHILD
Just remove / disconnect the leaf node that is to deleted from the tree

HIMANI DESHPANDE ( TSEC ) 90


CASE 2: A NODE HAS 1 CHILD
Just make the child of the deleting node, the child of its grandparent

HIMANI DESHPANDE ( TSEC ) 91


CASE 2: A NODE HAS 1 CHILD
Just make the child of the deleting node, the child of its grandparent

HIMANI DESHPANDE ( TSEC ) 92


CASE 3: A NODE HAS 2 CHILDREN
Method-1:
oVisit to the right subtree of the
deleting node. Smallest value in
right subtree
oPluck the smallest value element
called as inorder successor.
oReplace the deleting element with its
inorder successor.
oDelete the duplicate.

In Order : 2,10,12,15,16,17,19,20,30 HIMANI DESHPANDE ( TSEC ) 93


CASE 3: A NODE HAS 2 CHILDREN
Method-1:
oVisit to the right subtree of the
deleting node.
oPluck the smallest value element
called as inorder successor.
oReplace the deleting element with its
inorder successor.
oDelete the duplicate.

HIMANI DESHPANDE ( TSEC ) 94


CASE 3: A NODE HAS 2 CHILDREN
Method-2:
oVisit to the left subtree of the
deleting node. Largest value in
left subtree
oPluck the greatest value element
called as inorder predecessor.
oReplace the deleting element with its
inorder predecessor.
oDelete the duplicate.

In Order : 2,10,12,15,16,17,19,20,30
HIMANI DESHPANDE ( TSEC ) 95
CASE 3: A NODE HAS 2 CHILDREN
Method-2:
oVisit to the left subtree of the
deleting node.
oPluck the greatest value element
called as inorder predecessor.
oReplace the deleting element with its
inorder predecessor.
oDelete the duplicate.

HIMANI DESHPANDE ( TSEC ) 96


struct node *deleteNode( struct node *root, int key )
{
if(root == null)
root = root;
if(key > root -> data)
root -> right = deleteNode(root -> right, key);
else if(key < root -> data)
root -> left = deleteNode(root -> left, key);
else
{ //case 1 or case 2
if(root -> left == null)
{
struct node *temp = root -> right;
free(root);
return temp;
}
else if(root -> right == null)
{
struct node *temp = root -> left;
free(root);
return temp;
HIMANI DESHPANDE ( TSEC ) 97
}
else
{ //case 3
struct node *temp = smallest (root -> right);
root -> data = temp -> data;
root -> right = deleteNode(root -> right,
temp -> data);
}
return root;
}

HIMANI DESHPANDE ( TSEC ) 98


FINDING SMALLEST ELEMENT IN BST

Struct node *smallest(struct node *root)


{
if(root == null || (root -> left == null))
return root;
else
return smallest(root -> left);
}
Smallest element = 1

HIMANI DESHPANDE ( TSEC ) 99


FINDING LARGEST ELEMENT IN BST

Struct node *largest(struct node *root)


{
if(root == null || (root -> right == null)
return root;
else
return largest(root -> right);
}
Largest element = 14

HIMANI DESHPANDE ( TSEC ) 100


COUNTING TOTAL NO. OF NODES

int total_nodes(struct node *root)


{
if(root != null)
return ( total_nodes(root -> left) +
total_nodes(root -> right) +1);
else
return 0;
}
No. of nodes = 6

HIMANI DESHPANDE ( TSEC ) 101


COUNTING TOTAL NO. OF INTERNAL NODES

int internal_nodes(struct node *root)


{
if(root == null || (root -> left == null) && (root -
> right == null))
return 0;
else
return ( internal_nodes(root -> left) +
internal_nodes(root -> right) +1);
}
No. of internal nodes = 3

HIMANI DESHPANDE ( TSEC ) 102


COUNTING TOTAL NO. OF LEAF NODES

int leaf_nodes(struct node *root)


{
if(root == null)
return 0;
else if((root -> left == null) && (root -> right == null))
return 1;
else
return ( leaf_nodes(root -> left) + leaf_nodes(root -> right));
}
No. of leaf nodes = 3

HIMANI DESHPANDE ( TSEC ) 103


FINDING HEIGHT OF BST

int height(struct node *root)


{
if(root == null)
return -1;
else
{
int leftht=height(root -> left);
int rightht=height(root -> right);
return (max(leftht, rightht) + 1);
} Height of BST = 2
}
HIMANI DESHPANDE ( TSEC ) 104
INORDER

HIMANI DESHPANDE ( TSEC ) 105


POSTORDER

HIMANI DESHPANDE ( TSEC ) 106


PREORDER

HIMANI DESHPANDE ( TSEC ) 107


HIMANI DESHPANDE ( TSEC ) 108
HIMANI DESHPANDE ( TSEC ) 109
HIMANI DESHPANDE ( TSEC ) 110
APPLICATION OF
BINARY TREE

HIMANI DESHPANDE ( TSEC ) 111


EXPRESSION TREES

HIMANI DESHPANDE ( TSEC ) 112


EXPRESSION TREES
oIt is widely used to store algebraic expressions
oIt is a binary tree in which each internal node corresponds to operator &
each leaf node corresponds to operand

Example:
a + (b * c) + d * (e + f)

HIMANI DESHPANDE ( TSEC ) 113


EXPRESSION TREES
oIn-order traversal of expression tree gives infix expression

(a+(b*c))+(d*(e + f))

oPre-order traversal gives prefix expression

++a*bc*d+ef

oPost-order traversal gives postfix expression

abc*+def+*+
HIMANI DESHPANDE ( TSEC ) 114
EXPRESSIONS FROM GIVEN TREE

HIMANI DESHPANDE ( TSEC ) 115


EXPRESSIONS FROM GIVEN TREE

HIMANI DESHPANDE ( TSEC ) 116


CONSTRUCTING EXPRESSION TREE
oLet us consider a postfix expression for constructing an expression tree.
Following are the steps to construct an expression tree:

1. Read one symbol at a time from the postfix expression.

2. Check if the symbol is an operand or operator.


➢ If the symbol is an operand, create a one node tree and push a pointer onto
a stack
➢ If the symbol is an operator, pop two pointers from the stack, first pop
operand will be the right child & second will be the left child

3. A pointer to this new tree is pushed onto the stack


HIMANI DESHPANDE ( TSEC ) 117
CONSTRUCTING EXPRESSION TREE
Example: a b + c *

HIMANI DESHPANDE ( TSEC ) 118


CONSTRUCTING EXPRESSION TREE
ab+cde+**

HIMANI DESHPANDE ( TSEC ) 119


CONSTRUCTING EXPRESSION TREE
oIn prefix expression, we traverse left from the end of the expression
oFirst pop operand will be the left child & second will be the right child
Example:
++a*bc*d+ef

HIMANI DESHPANDE ( TSEC ) 120


Huffman Coding numerical is
frequently asked in exam

HUFFMAN ENCODING

HIMANI DESHPANDE ( TSEC ) 121


ENCODING
• Encoding and Decoding of messages consisting of set symbols
• Encoding can be done in two ways,
• Fixed Length
• Variable Length

HIMANI DESHPANDE ( TSEC ) 126


HUFFMAN ENCODING

•Consider an example, there is a message with 100 characters and there are only 4 distinct
characters with the following frequency.
a(50) b(30) c(15) d(5)
• In encoding, a character is represented with binary stream of 1's and 0's. Binary string which
represents a single character is codeword.
• In fixed length, codeword representing different characters have same length, whereas in
variable length, code word will have varying length.

HIMANI DESHPANDE ( TSEC ) 127


ENCODING
• Encoding can be done in two ways,
• Fixed Length
• Variable Length

HIMANI DESHPANDE ( TSEC ) 128


HUFFMAN CODING

Huffman coding is a tree based lossless data compression algorithm.

The idea is to assign variable-length codes to input characters,


lengths of the assigned codes are based on the frequencies of
corresponding characters.

HIMANI DESHPANDE ( TSEC ) 129


HUFFMAN EXAMPLE

HIMANI DESHPANDE ( TSEC ) 130


EXAMPLE

0 1

0 1 1
0

0
1

HIMANI DESHPANDE ( TSEC ) 131


HUFFMAN EXAMPLE
Initial String

Character Frequency Characters sorted according to the frequency

HIMANI DESHPANDE ( TSEC ) 132


HUFFMAN EXAMPLE

Create Tree

HIMANI DESHPANDE ( TSEC ) 133


Without encoding, the total size of
the string was 120(15*8) bits.
HUFFMAN EXAMPLE
After encoding the code size is
reduced to 28 bits

HIMANI DESHPANDE ( TSEC ) 134


HUFFMAN TREE EXAMPLE

HIMANI DESHPANDE ( TSEC ) 135


HUFFMAN TREE EXAMPLE

HIMANI DESHPANDE ( TSEC ) 136


HUFFMAN TREE EXAMPLE

HIMANI DESHPANDE ( TSEC ) 137


HUFFMAN TREE EXAMPLE

HIMANI DESHPANDE ( TSEC ) 138


HUFFMAN TREE
o Huffman tree is used for both encoding
and decoding of a message.

o Huffman tree is constructed based on the


frequency of the character of a given
message.

o Main Idea : To minimize, the length of the


encoded message by assigning a shorter
codeword or bit string to frequently
occurring symbols.

HIMANI DESHPANDE ( TSEC ) 139


CONSTRUCTING HUFFMAN CODES FROM HUFFMAN TREE
o Traverse the binary huffman tree from root to leaves.

o Print '0' for the left branch and print '1' for right branch.

o The accumulated 0's and 1's at each leaf constitutes the huffman
encoding corresponding the character.

HIMANI DESHPANDE ( TSEC ) 140


HUFFMAN CONSTRUCTION EXAMPLE
void Printcodes (struct node *temp, int arr[ ], int top)
{ if (temp -> left != null)
{
arr[top] = 0;
Printcodes(temp->left, arr, top+1)
}
if (temp -> right != null)
{
arr[top] = 1;
Printcodes(temp->right, arr, top+1)
}
If ( temp->left == null && temp->right == null)
{
printf("%c", temp->symbols);
printf("%d", temp->frequency);

for (int i=0; i<top; i++)


printf("%d", arr[I]);
}
} HIMANI DESHPANDE ( TSEC ) 141
BST ISSUES

HIMANI DESHPANDE ( TSEC ) 142


ISSUE WITH BST
Search time
The time it takes to search a BST is limited by the tree's height or depth. Each
step in the search process goes down one level.
Order of insertion of
nodes
Order of insertion of nodes
-> 50,40,35,30,20,10, 5
-> 30,40,10,50,20, 5,35
Height
=n
Height
= log(n)

HIMANI DESHPANDE ( TSEC ) 143


TIME COMPLEXITY

HIMANI DESHPANDE ( TSEC ) 144


BALANCED BINARY TREE

HIMANI DESHPANDE ( TSEC ) 145


WORST CASE

HIMANI DESHPANDE ( TSEC ) 146


SOLUTION TO BST ISSUE
→ AVL TREE

HIMANI DESHPANDE ( TSEC ) 147


AVL TREE

HIMANI DESHPANDE ( TSEC ) 148


AVL TREE
• Binary Tree with Balance condition
• AVL tree full form, named from their inventors, Adelson, Velskii & Landis
tree is binary search tree with a balance condition.
• The balance condition is determined by the difference between the
heights of subtrees of the root in the tree.

AVL tree ensures that Insertion, Deletion and Search operations take
O(log n) in both average and worst cases.
HIMANI DESHPANDE ( TSEC ) 149
AVL TREE
• An AVL tree is a binary tree in which heights of LST and RST of the root
differ utmost by 1, in which LST and RST of the root are again AVL trees.
• An empty BT is an AVL tree.
•A non-empty binary tree 'T' is an AVL tree iff given,
|HL - HR| <= 1
Where HL - HR is known as balance factor and for an AVL tree balance
factor of a node can be either 0, 1, -1.
• An AVL tree reduces skewness from tree.

HIMANI DESHPANDE ( TSEC ) 150


AVL TREE PROPERTY
AVL TREE
Balance Factor (k) =
height (left(k)) - height (right(k))

AVL tree is a balanced binary search tree in which


the height of left and right subtrees differ by no
more than one.

Allowed difference = -1,0,1


HIMANI DESHPANDE ( TSEC ) 151
REPRESENTATION USING LINKED LIST

typedef struct AVLNode1


{ char data;
left data bal right
int bal;
struct AVLNode1 *left;
struct AVLNode1 *right;
}
AVLNode ;

HIMANI DESHPANDE ( TSEC ) 152


TIME COMPLEXITY OF AVL TREE

HIMANI DESHPANDE ( TSEC ) 153


AVL INSERTION
Insertion in AVL tree is performed in the same way as it is
performed in a binary search tree. However, it may lead
to violation in the AVL tree property and therefore the tree
may need balancing. The tree can be balanced by
applying rotations.

HIMANI DESHPANDE ( TSEC ) 154


AVL INSERTION
Two phases

Phase 1 : Insertion is same as BST

Phase 2 : Rotations are applied to restore the balance factor of


search tree

HIMANI DESHPANDE ( TSEC ) 155


AVL INSERTION
Two phases
Phase 1 : Insertion is same as BST
Phase 2 : Rotations are applied to restore the balance factor of search tree.

To perform rotations, it is necessary to identify a specific node A,


✓whose balance factor is neither -1, 0, 1 and
✓it is the nearest ancestor to the inserted node on the path from the
inserted node to the root.
This implies that all other nodes in path from inserted node to node A,
will have balance factor either -1, 0, 1.
HIMANI DESHPANDE ( TSEC ) 156
AVL ROTATIONS
Based on position of inserted node with reference to node A.
There are four types of AVL rotations for Insertion

1. Left – Left Rotation


2. Right – Right Rotation
3. Left – Right Rotation
4. Right – Left Rotation
HIMANI DESHPANDE ( TSEC ) 157
AVL ROTATIONS

HIMANI DESHPANDE ( TSEC ) 158


AVL ROTATIONS
LEFT – LEFT ROTATION

HIMANI DESHPANDE ( TSEC ) 159


AVL ROTATIONS
LEFT – LEFT ROTATION

Balance of H is effected
B closest is child of H

HIMANI DESHPANDE ( TSEC ) 160


AVL ROTATIONS
LEFT – LEFT ROTATION
1. Inserted node is in LST of LST of node A.
2. Identify node B as left child of node A
3. To rebalance the AVL tree,
a) Node B will become root with BL and A as LST
and RST respectively.
b) BR and AR to be the LST and RST of node A
respectively.

HIMANI DESHPANDE ( TSEC ) 161


AVL ROTATIONS
Left – Left Rotation Example

HIMANI DESHPANDE ( TSEC ) 162


AVL ROTATIONS
RIGHT – RIGHT ROTATION

HIMANI DESHPANDE ( TSEC ) 163


AVL ROTATIONS
RIGHT – RIGHT ROTATION
1. Inserted node is in RST of RST of node A.
2. Identify node B as right child of node A
3. To rebalance the AVL tree,
a) Node B will become root with A and BR as
LST and RST respectively.
b) AL and BL to be the LST and RST of node A
respectively.

HIMANI DESHPANDE ( TSEC ) 164


AVL ROTATIONS
Right – Right Rotation Example

HIMANI DESHPANDE ( TSEC ) 165


AVL ROTATIONS
LEFT – RIGHT ROTATION

Convert LR → LL HIMANI DESHPANDE ( TSEC ) 166


AVL ROTATIONS
LEFT – RIGHT ROTATION

Convert LR → LL HIMANI DESHPANDE ( TSEC ) 167


AVL ROTATIONS
LEFT – RIGHT ROTATION

Convert LR → LL Trick→ Middle element will become the root


HIMANI DESHPANDE ( TSEC ) 168
AVL ROTATIONS
LEFT – RIGHT ROTATION
1. Inserted node is in RST of LST of node A.
2. Identify node B as left child of node A.
3. Identify node C as right child of node B.
4. To rebalance the AVL tree,
a) Node C will become root with B and A
as LST and RST respectively.
b) BL and CL to be the LST and RST of node
B respectively.
c) CR and AR to be the LST and RST of node
A respectively.

HIMANI DESHPANDE ( TSEC ) 169


AVL ROTATIONS
Left – Right Rotation Example

HIMANI DESHPANDE ( TSEC ) 170


AVL ROTATIONS
RIGHT – LEFT ROTATION

Convert RL → RR HIMANI DESHPANDE ( TSEC ) 171


AVL ROTATIONS
RIGHT – LEFT ROTATION

Convert RL → RR 2 rotations HIMANI DESHPANDE ( TSEC ) 172


AVL ROTATIONS
RIGHT – LEFT ROTATION

Convert RL → RR Trick→ Middle element will become the root


HIMANI DESHPANDE ( TSEC ) 173
AVL ROTATIONS
RIGHT – LEFT ROTATION
Right - Left Rotation
1. Inserted node is in LST of RST of node A.
2. Identify node B as right child of node A.
3. Identify node C as left child of node B.
4. To rebalance the AVL tree,
a) Node C will become root with A and B
as LST and RST respectively.
b) AL and CL to be the LST and RST of
node A respectively.
c) CR and BR to be the LST and RST of
node B respectively.
HIMANI DESHPANDE ( TSEC ) 174
AVL ROTATIONS
Right – Left Rotation Example

HIMANI DESHPANDE ( TSEC ) 175


LR ROTATION
LR RR Balanced

HIMANI DESHPANDE ( TSEC ) 176


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

11 17
L
7 53
L
4

LL

HIMANI DESHPANDE ( TSEC ) 177


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

7 17

4 11 53

13

BALANCED

HIMANI DESHPANDE ( TSEC ) 178


AVL Tree Example:
• Now insert 12
14

7 17

4 11 53
R
13
L
12
RL

HIMANI DESHPANDE ( TSEC ) 179


AVL Tree Example:
• Now insert 12
14

7 17

4 11 53
R
12
R
13
RR

HIMANI DESHPANDE ( TSEC ) 180


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

7 17

4 12 53

11 13

BALANCED

HIMANI DESHPANDE ( TSEC ) 181


AVL Tree Example:
• Now insert 8

14

7 17
R
4 12 53
L
11 13

8
RL

HIMANI DESHPANDE ( TSEC ) 182


AVL Tree Example:
• Now insert 8
14

7 17
R
4 11 53
R
8 12

13
RR

HIMANI DESHPANDE ( TSEC ) 183


AVL Tree Example:
Now the AVL tree is balanced.
14

11 17

7 12 53

4 8 13

Balanced

HIMANI DESHPANDE ( TSEC ) 184


AVL Tree Example:
• Now DELETE 53
14

11 17

7 12 53

4 8 13

HIMANI DESHPANDE ( TSEC ) 185


AVL Tree Example:
• Now remove 53, unbalanced

14
L
11 17
L
7 12

4 8 13

LL

HIMANI DESHPANDE ( TSEC ) 186


AVL Tree Example:
• Balanced! Remove 11

11

7 14

4 8 12 17

13

Balanced
Use Inorder predecessor

HIMANI DESHPANDE ( TSEC ) 187


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

7 14

4 12 17

13

HIMANI DESHPANDE ( TSEC ) 188


AVL Tree Example:
• Remove 8

7 14

4 12 17

13

Use Inorder predecessor

HIMANI DESHPANDE ( TSEC ) 189


AVL Tree Example:
unbalanced

7
R
4 14
L
12 17

13

RL

HIMANI DESHPANDE ( TSEC ) 190


AVL Tree Example:
• Remove 8, unbalanced

7
R
4 12
R
14

13 17

RR

HIMANI DESHPANDE ( TSEC ) 191


AVL Tree Example:
• Balanced!!

12

7 14

4 13 17

Balanced

HIMANI DESHPANDE ( TSEC ) 192


EXERCISES
Build an AVL tree with the following values:
15, 20, 24, 10, 13, 7, 30, 36, 25

HIMANI DESHPANDE ( TSEC ) 193


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
HIMANI DESHPANDE ( TSEC ) 194
15, 20, 24, 10, 13,
15, 20, 24, 7, 30,
10, 13, 36,
7, 30, 36, 25
25

20
13

13 24 10 20

10 15 7 15 24

7 30

13 36

10 20

7 15 30

24 36

HIMANI DESHPANDE ( TSEC ) 195


15, 20, 24, 10, 13, 7, 30, 36, 25
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

HIMANI DESHPANDE ( TSEC ) 196


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
HIMANI DESHPANDE ( TSEC ) 197
AVL INSERTION EXAMPLE
Construct an AVL Tree for the following set of element to be inserted one by one.
13, 15, 20, 7, 10, 1, 18, 25, 16

HIMANI DESHPANDE ( TSEC ) 198


AVL INSERTION EXAMPLE
Construct an AVL Tree for the following set of element to be inserted one by one.
13, 15, 20, 7, 10, 1, 18, 25, 16

HIMANI DESHPANDE ( TSEC ) 199


AVL INSERTION EXAMPLE
Construct an AVL Tree for the following set of element to be inserted one by one.
13, 15, 20, 7, 10, 1, 18, 25, 16

HIMANI DESHPANDE ( TSEC ) 200


AVL INSERTION EXAMPLE
Construct an AVL Tree for the following set of element to be inserted one by one.
13, 15, 20, 7, 10, 1, 18, 25, 16

HIMANI DESHPANDE ( TSEC ) 201


AVL
DELETION
HIMANI DESHPANDE ( TSEC ) 202
AVL DELETION X
Two phases
Phase 1 : Deletion is same as BST
Phase 2 : Rotations need to be applied in case
imbalance.

On deletion of a node X from AVL tree,


A
let node A be the closest ancestor node on the
path from X to the root node,
with balance factor as +2 or -2.

HIMANI DESHPANDE ( TSEC ) 203


AVL DELETION A Critical
node
Two phases
Phase 1 : Deletion is same as BST B
Phase 2 : Rotations need to be applied in case imbalance.
X
On deletion of a node X from AVL tree, let node A be the closest ancestor
node on the path from X to the root node, with balance factor as +2 or -2.

To restore the balance, rotations are first classified as


L or R depending on whether the deletion occurred on the
LST or RST of node A.
A is parent of X
Now identify node B, which will be root of LST or RST of B is sibling of X
node A.
HIMANI DESHPANDE ( TSEC ) 204
A Critical
node

AVL DELETION X B

Two phases
Phase 1 : Deletion is same as BST
Phase 2 : Rotations need to be applied in case imbalance.

If the node which is to be deleted is present in the left sub-tree of the critical node, then L rotation
needs to be applied
If the node which is to be deleted is present in the right sub-tree of the critical node, the R rotation
will be applied.
Based on balance factor of node B, rotations are further classified as
•R0 , R1 , R-1
•L0 , L1 , L-1
HIMANI DESHPANDE ( TSEC ) 205
✓ Which side child is deleted
AVL DELETION ✓ Check balance factor of sibling

R o → LL
R 1 → LL
R -1 → LR
Rotation
Delete 30
HIMANI DESHPANDE ( TSEC ) 206
R0 rotation (Node B has balance factor 0 )

AVL DELETION ✓ Which side child is deleted


✓ Check balance factor of sibling

HIMANI DESHPANDE ( TSEC ) 207


R0 rotation (Node B has balance factor 0 )

AVL DELETION ✓ Which side child is deleted


✓ Check balance factor of sibling

HIMANI DESHPANDE ( TSEC ) 208


R0 rotation (Node B has balance factor 0 )

AVL DELETION ✓ Which side child is deleted


✓ Check balance factor of sibling

R o → LL

HIMANI DESHPANDE ( TSEC ) 209


R0 ROTATIONS

HIMANI DESHPANDE ( TSEC ) 210


AVL DELETION
✓ Which side child is deleted
✓ Check balance factor of sibling

R o → LL L o → RR
R 1 → LL L 1 → RL
R -1 → LR L -1 → RR
HIMANI DESHPANDE ( TSEC ) 211
R1 Rotation (Node B has balance factor 1)
AVL DELETION ✓ Which side child is deleted
✓ Check balance factor of sibling

HIMANI DESHPANDE ( TSEC ) 212


R1 Rotation (Node B has balance factor 1)

AVL DELETION
R 1 → LL

HIMANI DESHPANDE ( TSEC ) 213


R1 ROTATIONS

HIMANI DESHPANDE ( TSEC ) 214


R-1 Rotation (Node B has balance factor -1)

AVL DELETION
R -1 → LR

HIMANI DESHPANDE ( TSEC ) 215


R-1 ROTATIONS

HIMANI DESHPANDE ( TSEC ) 216


AVL DELETION
✓ Which side child is deleted
✓ Check balance factor of sibling

L o → RR
L 1 → RL
L -1 → RR
HIMANI DESHPANDE ( TSEC ) 217
L0

HIMANI DESHPANDE ( TSEC ) 218


L o → RR
L0

HIMANI DESHPANDE ( TSEC ) 219


L0 ROTATIONS

HIMANI DESHPANDE ( TSEC ) 220


L -1 → RR
L-1 ROTATIONS

HIMANI DESHPANDE ( TSEC ) 221


L1 ROTATIONS L 1 → RL

HIMANI DESHPANDE ( TSEC ) 222


AVL DELETION EXAMPLE

HIMANI DESHPANDE ( TSEC ) 223


AVL DELETION EXAMPLE

Note: Unlike insertion in case of deletion we not only need to re-balance the subtree
where the first imbalance has occurred but also its unbalanced ancestors too.224
HIMANI DESHPANDE ( TSEC )
B-Trees

HIMANI DESHPANDE ( TSEC ) 225


DEFINITION OF A B-TREE
A B-tree of order m is an m-way tree (i.e., a tree where each node
may have up to m children) in which:

➢the number of keys in each non-leaf node is one less than the number of its
children and these keys partition the keys in the children in the fashion of a
search tree
➢all leaves are on the same level
➢all non-leaf nodes except the root have at least m / 2 children
➢the root is either a leaf node, or it has from two to m children
➢a leaf node contains no more than m – 1 keys
The number ‘m’ should always be odd
HIMANI DESHPANDE ( TSEC
226)
A B-tree of order 5
AN EXAMPLE B-TREE containing 26 items
26

6 12

42 51 62
1 2 4 7 8 13 15 18 25

27 29 45 46 48 53 55 60 64 70 90

Note that all the leaves are at the same level HIMANI DESHPANDE ( TSEC )
CONSTRUCTING A B-TREE
Suppose we start with an empty B-tree and keys arrive in the following order:
1 12 8 2 25 6 14 28 17 7 52 16 48 68 3 26 29 53 55 45
We want to construct a B-tree of degree 5

The first four items go into the root:

1 2 8 12 1 2 8 12

To put the fifth item in the root would violate condition 5


Therefore, when 25 arrives, pick the middle key to make a new root
HIMANI DESHPANDE ( TSEC ) 228
1
12
8
2
CONSTRUCTING A B-TREE
25 Add 6 to the tree
6
14
28
17
7 Exceeds Order.
52 Promote middle and
16 split.
48 1 2 8 12 25
68
3
26
29
53
55
45
HIMANI DESHPANDE ( TSEC ) 229
1
12
8 CONSTRUCTING A B-TREE (CONTD.)
2
25 8
6
14
28
17
7 1 2 12 25
52
16
48
68
3
26
29
53
55
45
HIMANI DESHPANDE ( TSEC ) 230
1
12
8 CONSTRUCTING A B-TREE (CONTD.)
2
25 8
6
14
28
17
7 1 2 12 25
52
16
48 6, 14, 28 get added to the leaf nodes:
68
3 8
26
29
53
55
45 1 2
1 6
2 12 14
25 28
HIMANI DESHPANDE ( TSEC ) 231
1
12
8 CONSTRUCTING A B-TREE (CONTD.)
2
25 8
6
14
28
17
7 1 2 12 25
52
16
48 6, 14, 28 get added to the leaf nodes:
68
3 8
26
29
53
55
45 1 2
1 6
2 12 14 25 28
HIMANI DESHPANDE ( TSEC ) 232
1
12
8
2 CONSTRUCTING A B-TREE (CONTD.)
25
6 Adding 17 to the right leaf node would over-fill it, so we take
14 the middle key, promote it (to the root) and split the leaf
28
17
7 8
52
16
48
68
3 1 2 6
2 25 28 28
12 14 17
26
29
53
55
45

HIMANI DESHPANDE ( TSEC ) 233


1
12
8
2 CONSTRUCTING A B-TREE (CONTD.)
25 7, 52, 16, 48 get added to the leaf nodes
6
14
28
17
7 8 17
52
16
48
68
3 1 2 76 12 14
16 25 28 52
48
26
29
53
55
45

HIMANI DESHPANDE ( TSEC ) 234


1
12
8 CONSTRUCTING A B-TREE (CONTD.)
2
25 Adding 68 causes us to split the right most leaf,
6 promoting 48 to the root
14
28
17
7
52
16 8 17
48
68
3
26 1 2 6 7 12 14 16 25 28 48 52 68
29
53
55
45
HIMANI DESHPANDE ( TSEC ) 235
1
12
8
CONSTRUCTING A B-TREE (CONTD.)
2
25 Adding 3 causes us to split the left most leaf
6
14
28 8 17 48
17
7
52
16 1 2
3 6 7 12 14 16 25 28 52 68
48
68
3
26
29
53
55
45
HIMANI DESHPANDE ( TSEC ) 236
1

CONSTRUCTING A B-TREE (CONTD.)


12
8
2
25 Add 26, 29, 53, 55 then go into the leaves
6
14
28 3 8 17 48
17
7
52
16
48 1 2 6 7 12 14 16 25262829 52536855
68
3
26
29
53
55
45

HIMANI DESHPANDE ( TSEC ) 237


1
12
8
2
CONSTRUCTING A B-TREE (CONTD.)
Exceeds Order.
25 Add 45 increases the trees level Promote middle and
6
14 split.
28
17
7 Exceeds Order.
52 Promote middle and
16 3 8 17 48 split.
48
68
3
26 1 2 6 7 12 14 16 25 26 28 29 45 52 53 55 68
29
53
55
45

HIMANI DESHPANDE ( TSEC ) 238


CONSTRUCTING A B-TREE
Suppose we start with an empty B-tree and keys arrive in the following order:1 12
8 2 25 5 14 28 17 7 52 16 48 68 3 26 29 53 55 45
We want to construct a B-tree of order 5
The first four items go into the root:

1 2 8 12

To put the fifth item in the root would violate condition 5


Therefore, when 25 arrives, pick the middle key to make a new root

HIMANI DESHPANDE ( TSEC


239)
CONSTRUCTING A B-TREE (CONTD.)
8

1 2 12 25

6, 14, 28 get added to the leaf nodes:

1 2 6 12 14 25 28

HIMANI DESHPANDE ( TSEC


240)
CONSTRUCTING A B-TREE (CONTD.)
Adding 17 to the right leaf node would over-fill it, so we take the
middle key, promote it (to the root) and split the leaf
8 17

1 2 6 12 14 25 28

7, 52, 16, 48 get added to the leaf nodes


8 17

1 2 6 7 12 14 16 25 28 48 52

HIMANI DESHPANDE ( TSEC


241)
CONSTRUCTING A B-TREE (CONTD.)
Adding 68 causes us to split the right most leaf, promoting 48 to the root,
and
adding 3 causes us to split the left most leaf, promoting 3 to the root; 26, 29,
53, 55 then go into the leaves
3 8 17 48

1 2 6 7 12 14 16 25 26 28 29 52 53 55 68

Adding 45 causes a split of 25 26 28 29

and promoting 28 to the root then causes the root to split

HIMANI DESHPANDE ( TSEC


242)
CONSTRUCTING A B-TREE (CONTD.)
17

3 8 28 48

1 2 6 7 12 14 16 25 26 29 45 52 53 55 68

HIMANI DESHPANDE ( TSEC


243)
INSERTING INTO A B-TREE
Attempt to insert the new key into a leaf
If this would result in that leaf becoming too big, split the leaf into two, promoting the
middle key to the leaf’s parent
If this would result in the parent becoming too big, split the parent into two, promoting
the middle key
This strategy might have to be repeated all the way to the top
If necessary, the root is split in two and the middle key is promoted to a new root,
making the tree one level higher

HIMANI DESHPANDE ( TSEC


244)
EXERCISE IN INSERTING A B-TREE
Insert the following keys to a 5-way B-tree:
3, 7, 9, 23, 45, 1, 5, 14, 25, 24, 13, 11, 8, 19, 4, 31, 35, 56

HIMANI DESHPANDE ( TSEC


245)
REMOVAL FROM A B-TREE
During insertion, the key always goes into a leaf. For deletion we wish to remove
from a leaf. There are three possible ways we can do this:

1 - If the key is already in a leaf node, and removing it doesn’t cause that leaf
node to have too few keys, then simply remove the key to be deleted.

2 - If the key is not in a leaf then it is guaranteed (by the nature of a B-tree) that
its predecessor or successor will be in a leaf -- in this case we can delete the key
and promote the predecessor or successor key to the non-leaf deleted key’s
position.

HIMANI DESHPANDE ( TSEC


246)
REMOVAL FROM A B-TREE (2)
If (1) or (2) lead to a leaf node containing less than the minimum number of keys then
we have to look at the siblings immediately adjacent to the leaf in question:
 3: if one of them has more than the min. number of keys then we can promote one of its keys to the
parent and take the parent key into our lacking leaf
 4: if neither of them has more than the min. number of keys then the lacking leaf and one of its
neighbours can be combined with their shared parent (the opposite of promoting a key) and the new
leaf will have the correct number of keys; if this step leave the parent with too few keys then we
repeat the process up to the root itself, if required

HIMANI DESHPANDE ( TSEC


247)
TYPE #1: SIMPLE LEAF DELETION
Assuming a 5-way
B-Tree, as before... 12 29 52

22 7 9 15 22 31 43 56 69 72

Delete 2: Since there are enough


keys in the node, just delete it

HIMANI DESHPANDE ( TSEC


248)
TYPE #1: SIMPLE LEAF DELETION
Assuming a 5-way
B-Tree, as before... 12 29 52

2 7 9 15 22 31 43 56 69 72

Delete 2: Since there are enough


keys in the node, just delete it

HIMANI DESHPANDE ( TSEC


249)
TYPE #1: SIMPLE LEAF DELETION
Assuming a 5-way
B-Tree, as before... 12 29 52

2 7 9 15 22 31 43 56 69 72

HIMANI DESHPANDE ( TSEC


250)
TYPE #2: SIMPLE NON-LEAF DELETION
12 29 56
52 Delete 52

7 9 15 22 31 43 56 69 72

Borrow the predecessor


or (in this case) successor

HIMANI DESHPANDE ( TSEC


251)
TYPE #4: TOO FEW KEYS IN NODE AND ITS
SIBLINGS
12 29 56

Join back together

7 9 15 22 31 43 69 72
Too few keys!
Delete 72

HIMANI DESHPANDE ( TSEC


252)
TYPE #4: TOO FEW KEYS IN NODE AND ITS
SIBLINGS
12 29

7 9 15 22 31 43 56 69

HIMANI DESHPANDE ( TSEC


253)
TYPE #3: ENOUGH SIBLINGS
12 29
Demote root key and
promote leaf key

7 9 15 22 31 43 56 69

Delete 22

HIMANI DESHPANDE ( TSEC


254)
TYPE #3: ENOUGH SIBLINGS
12 31

7 9 15 29 43 56 69

HIMANI DESHPANDE ( TSEC


255)
EXERCISE IN REMOVAL FROM A B-TREE
Given 5-way B-tree created by these data (last exercise):
3, 7, 9, 23, 45, 1, 5, 14, 25, 24, 13, 11, 8, 19, 4, 31, 35, 56

Add these further keys: 2, 6,12

Delete these keys: 4, 5, 7, 3, 14

HIMANI DESHPANDE ( TSEC


256)
B+ TREE
HIMANI DESHPANDE ( TSEC
257)
B+ TREE
B+ Tree is an extension of B Tree which allows efficient insertion,
deletion and search operations.
❑In B Tree, Keys and records both can be stored in the internal as well as leaf
nodes. Whereas, in B+ tree, records (data) can only be stored on the leaf
nodes while internal nodes can only store the key values.
❑The leaf nodes of a B+ tree are linked together in the form of a singly linked
lists to make the search queries more efficient.
❑Internal nodes (keys to access records) of the B+ tree are stored in the main
memory whereas, leaf nodes are stored in the secondary memory.d

HIMANI DESHPANDE ( TSEC


258)
B+ TREE OF ORDER 3

HIMANI DESHPANDE ( TSEC


259)
B vs B+ Tree

Advantages of B+ trees:
•Because B+ trees don't have data associated with interior nodes, more keys can fit on a page of memory.
Therefore, it will require fewer cache misses in order to access data that is on a leaf node.
•The leaf nodes of B+ trees are linked, so doing a full scan of all objects in a tree requires just one linear pass
through all the leaf nodes. A B tree, on the other hand, would require a traversal of every level in the tree.
This full-tree traversal will likely involve more cache misses than the linear traversal of B+ leaves.
HIMANI DESHPANDE ( TSEC ) 260
B vs B+ Tree

Advantages of B trees:

•Because B trees contain data with each key, frequently accessed nodes can lie closer to the root, and
therefore can be accessed more quickly.

HIMANI DESHPANDE ( TSEC ) 261


B Tree B+ Tree
1 Search keys can not be repeatedly stored. Redundant search keys can be present.
Data can be stored in leaf nodes as well
2 as internal nodes
Data can only be stored on the leaf nodes.

Searching for some data is a slower


process since data can be found on Searching is comparatively faster as data can
3 internal nodes as well as on the leaf only be found on the leaf nodes.
nodes.
Deletion will never be a complexed process
Deletion of internal nodes are so
4 complicated and time consuming.
since element will always be deleted from the
leaf nodes.
Leaf nodes are linked together to make the
5 Leaf nodes can not be linked together.
search operations more efficient.

HIMANI DESHPANDE ( TSEC ) 262


INSERTION IN B+ TREE

Step 1: Insert the new node as a leaf node

Step 2: If the leaf doesn't have required space, split the node and copy the
middle node to the next index node.

Step 3: If the index node doesn't have required space, split the node and
copy the middle element to the next index page.

HIMANI DESHPANDE ( TSEC


263)
EXAMPLE

HIMANI DESHPANDE ( TSEC


264)
EXAMPLE

HIMANI DESHPANDE ( TSEC


265)
DELETION IN B+ TREE
Step 1: Delete the key and data from the leaves.

Step 2: if the leaf node contains less than minimum number of elements, merge
down the node with its sibling and delete the key in between them.

Step 3: if the index node contains less than minimum number of elements,
merge the node with the sibling and move down the key in between them.

HIMANI DESHPANDE ( TSEC


266)
EXAMPLE

HIMANI DESHPANDE ( TSEC


267)
EXAMPLE

HIMANI DESHPANDE ( TSEC


268)
HIMANI DESHPANDE ( TSEC ) 269
THANK YOU .
.
HIMANI DESHPANDE ( TSEC ) 270

You might also like