Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CHAPTER 8 - TREESds

Download as pdf or txt
Download as pdf or txt
You are on page 1of 122

Chapter - 8

TREES
TREE

A tree is a non-linear data structure which describes the hierarchical relationships between a
finite set of elements called nodes. One of the nodes is designated as root node while the
remaining set of nodes are grouped into subsets which itself is a tree. The hierarchical
relationships are described by referring to each subtree as a child of the root, while the root is
referred to as the parent of each tree.

Basic terminology
 A tree consists of finite set of elements, called nodes, and a finite set of directed lines
called branches, that connect the nodes.

 The number of branches associated with a node is the degree of the node.

 When the branch is directed toward the node, it is in-degree branch.

 When the branch is directed away from the node, it is an out-degree branch.

 The sum of the in-degree and out-degree branches is the degree of the node.

 If the tree is not empty, the first node is called the root.

 The in-degree of the root is, by definition, zero.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 1


 With the exception of the root, all of the nodes in a tree must have an in-degree of
exactly one; that is, they may have only one predecessor.

 All nodes in the tree can have zero, one, or more branches leaving them; that is, they
may have out-degree of zero, one, or more.

 A leaf is any node with an out-degree of zero, that is, a node with no successors.

 A node that is not a root or a leaf is known as an internal node.

 A node is a parent if it has successor nodes; that is, if it has out-degree greater than
zero.

 A node with a predecessor is called a child.

 Two or more nodes with the same parents are called siblings.

 An ancestor is any node in the path from the root to the node.

 A descendant is any node in the path below the parent node; that is, all nodes in the
paths from a given node to a leaf are descendants of that node.

 A path is a sequence of nodes in which each node is adjacent to the next node.

 The level of a node is its distance from the root. The root is at level 0, its children are
at level 1, etc.

 The height of the tree is the level of the leaf in the longest path from the root plus 1.
By definition the height of any empty tree is -1.

 A sub-tree is any connected structure below the root. The first node in the sub-tree is
known is the root of the sub-tree.

Example:

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 2


BINARY TREES
A binary tree is a tree in which no node can have more than two sub-trees; the maximum out-
degree for a node is two. In other words, a node can have zero, one, or two sub-trees. These sub-
trees are designated as the left sub-tree and the right sub-tree.

Properties of Binary Trees

1) Given that we need to store N nodes in a binary tree, the maximum height is H max  N

2) The minimum height of a binary tree is determined as follows: H min  log2 N   1

3) Given a height of the binary tree, H, the minimum number of nodes in the tree is given as
follows: N
min  H

4) Given a height of the binary tree, H, the maximum number of nodes in the tree is given as

max  2 1
follows: N H

5) The children of any node in a tree can be accessed by following only one branch path, the one
that leads to the desired node.

6) The nodes at level 1, which are children of the root, can be accessed by following only one
branch; the nodes of level 2 of a tree can be accessed by following only two branches from the
root, etc.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 3


Complete Binary Trees

 A complete tree has the maximum number of entries for its height. The maximum
number is reached when the last level is full.

 A tree is considered nearly complete if it has the minimum height for its nodes and all
nodes in the last level are found on the left.

Converting General trees to Binary trees

1) Identify the leftmost children in the tree

2) Connect Siblings

3) Delete Unneeded branches

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 4


The resulting tree will be a Binary tree is

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 5


Operations on Binary trees using Arrays
Inserting an element into the Binary trees using Arrays

Method:

In order to insert a new element into a Binary tree we need to search for the leaf node in either of
sub-trees and then we insert the element as the next element to the leaf node in either of the trees.

Algorithm BSTInsert(tree, int item, LEFT, RIGHT)

// This algorithm inserts an element into the Binary tree

1) if(tree==NULL)

2) if[(A[2*I]=NULL) && (A[2*I+1]=NULL)]

3) // Traverse the left sub-tree

if[(A[2*I]=NULL)

// Insert new element

A[2*I]= Item;

else

4) // Traverse the right sub-tree

if[(A[2*I+1]=NULL)

// Insert new element

A[2*I+1]= Item; }}

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 6


Deleting an element from a Binary tree using Arrays

Method:

In order to delete an element from a Binary tree we need to search for the leaf node in either of
sub-trees and then we delete the element the leaf node in either of the sub-trees.

Algorithm DeleteBST(tree, int item, LEFT, RIGHT)

// This algorithm deletes an element from the Binary tree

1) if(tree==NULL)

2) if[(A[2*I]=NULL) && (A[2*I+1]=NULL)]

3) // Traverse the left sub-tree

if[(A[2*I]=NULL)

// Delete element

A[2*I]= NULL;

else

4) // Traverse the right sub-tree

if[(A[2*I+1]=NULL)

// Delete element

A[2*I+1]= NULL;

}
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 7
4) Binary tree Traversals

A traversal is a process that visits all the nodes in the tree. Since a tree is a nonlinear data
structure, there is no unique traversal. The traversal algorithms are grouped in the following two
kinds:

 Pre-order traversal
 In-order traversal
 Post-order traversal

The binary tree for traversals is

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 8


Pre-order traversal

Method:

1) Process the root node in pre-order

2) Traverse the left sub-tree in pre-order

3) Traverse the right sub-tree in pre-order

Pre-order traversal is ABCDEF

Algorithm Preorder (tree, int data, Left, Right)

// This algorithm performs the Preorder traversal of the Binary tree

1) if (tree != NULL)

2) // Process the root node of the tree in pre-order

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 9


Print: tree[data];

3) // Traverse the left sub-tree in pre-order

Preorder(tree[left], data);

4) // Traverse the right sub-tree in pre-order

Preorder(tree[right], data);

In-order traversal

Method:

1) Traverse the left sub-tree in in-order

2) Process the root node in in-order

3) Traverse the right sub-tree in in-order

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 10


In-order traversal is CBDAEF

Algorithm Inorder(tree, int data, Left, Right)

// This algorithm performs the Preorder traversal of the Binary tree

1) if (tree != NULL)

2) // Traverse the left sub-tree in in-order

Inorder(tree[left], data);

3) // Process the root node of the tree in in-order

Print: tree[data];

4) // Traverse the right sub-tree in in-order

Inorder(tree[right], data);

Post-order traversal

Method:

1) Traverse the left sub-tree in Post-order

2) Traverse the right sub-tree in Post-order

3) Process the root node in Post-order

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 11


Postorder traversal is CDBFEA

Algorithm Postorder(tree, int data, Left, Right)

// This algorithm performs the Preorder traversal of the Binary tree

1) if (tree != NULL)

2) // Traverse the left sub-tree in post-order

Postorder(tree[left], data);

3) // Traverse the right sub-tree in in-order

Postorder(tree[right], data);

4) // Process the root node of the tree in post-order

Print: tree[data];

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 12


Operations on Binary trees using Linked list

1) Creating a Binary tree

Algorithm CreateBinarytree(TREE * tree)

// This algorithm dynamically allocates memory for a node and creates the head structure for the
tree.

// Local declarations

int data;

1) // Check whether the tree is empty

if(TREECOUNT=0)

tree = (TREE*tree)malloc(sizeof(TREE*tree);

tree->data = data;

2) // Set the left child link to null

tree->left = NULL;

3) // Set the right child link to null

tree ->right = NULL;

4) return(tree);

2) Inserting a node into a Binary tree

Algorithm InsertBST(TREE * tree, int data, Node *Pnew)

// This algorithm inserts an element into the Binary tree

1) if(tree==NULL)

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 13


Pnew = (TREE*tree)malloc(sizeof(TREE*tree)

tree= Pnew;

tree->data = data;

tree->left = NULL;

tree ->right = NULL;

else

2) if(tree->left=NULL)

tree->left = InsertBST(root->left, Pnew);

else

3) if(tree->right=NULL)

tree->right = InsertBST(root->right, Pnew);

4) (TREECOUNT )++;

5) return(tree);

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 14


3) Deleting a node from a Binary tree

Algorithm DeleteBST(TREE * tree, int data)

// This algorithm inserts an element into the Binary tree

1) if(tree!=NULL)

2) if(tree->left!=NULL)&& if(tree->right!=NULL)

if(tree->left!=NULL)

tree->left = NULL;

else

3) if(tree->right!=NULL)

tree->right = NULL;

4) (TREECOUNT)--;

5) return(tree);

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 15


4) Binary tree Traversals

Algorithm Preorder (TREE * tree, int data)

// This algorithm performs the Preorder traversal of the Binary tree

1) if (tree != NULL)

2) // Process the root node of the tree in pre-order

Print: tree  data;

3) // Traverse the left sub-tree in pre-order

Preorder(treeleft, data);

4) // Traverse the right sub-tree in pre-order

Preorder(treeright, data);

5) return(tree);

Algorithm Inorder(TREE * tree, int data)

// This algorithm performs the Preorder traversal of the Binary tree

1) if (tree != NULL)

2) // Traverse the left sub-tree in in-order

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 16


Inorder(treeleft, data);

3) // Process the root node of the tree in in-order

Print: tree  data;

4) // Traverse the right sub-tree in in-order

Inorder(treeright, data);

5) return(tree);

Algorithm Postorder(TREE * tree, int data)

// This algorithm performs the Preorder traversal of the Binary tree

1) if (tree != NULL)

2) // Traverse the left sub-tree in post-order

Postorder(treeleft, data);

3) // Traverse the right sub-tree in in-order

Postorder(treeright, data);

4) // Process the root node of the tree in post-order

Print: tree  data;

5) return(tree); }

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 17


Problem 1:

The Binary tree for traversals is

Pre-order - 8, 5, 9, 7, 1, 12, 2, 4, 11, 3


In-order - 9, 5, 1, 7, 2, 12, 8, 4, 3, 11
Post-order - 9, 1, 2, 12, 7, 5, 3, 11, 4, 8

RECONSTRUCTING BINARY TREES

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 18


Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 19
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 20
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 21
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 22
Problem 2: Construct a binary tree from given Post-order and Pre-order traversals. Given
traversals:

Pre-order: 50, 25, 12, 37, 30, 40, 75, 62,60, 70, 87

Post-order: 12, 30, 40, 37, 25, 60, 70, 62, 87, 75, 50

Find the In-order traversal of the tree.

Solution:

1. The first element in the pre-order traversal is the root of the tree. So, here 50 will be the root of
the tree.

2. We will find the index of element next to 50 i.e. 25 in the post-order traversal. The index
found is 4. Let this index is denoted by 'pos'.

3. All the elements to the left of this index and element at this index (i.e. from 0 to 4 index) will
be in the left sub-tree of 50.

4. And all the elements to the right of this index (from 6 to 10) will be in the right sub-tree of 50.
Now the structure of tree is:

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 23


The following binary tree is obtained:

Problem 3:

Construct a binary tree from in-order and post-order traversals.

In-order Traversal: 4, 2, 1, 7, 5, 8, 3, 6

Post-order Traversal: 4, 2, 7, 8, 5, 6, 3, 1

Find the Pre-order traversal of the tree.

Solution:

1) Root would be the last element in the post-order sequence i.e. 1.

2) Next locate the index of the root node in the in-order sequence.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 24


3) Since 1 is the root node all nodes before 1 in In-order sequence must be included in the left
sub-tree of the root node i.e. {4, 2} and all the nodes after 1 must be included inthe right sub-tree
of the root i.e. {7,5,8,3,6}.

4) Now the problem is reduced to building left and right sub-trees and linking them to the root
node.

The Pre-order traversal: 1,4,2,5,7,8,3,6

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 25


COUNTING THE NUMBER OF BINARY TREES

Number of distinct Binary trees possible with n labeled nodes is (2n!) / (n+1)!

If the nodes are similar (unlabeled), then the no. of distinct binary trees will be the above value
divided by the no. of distinct permutations possible for a binary tree structure, which will be n!
for a tree with n nodes.

(2n)! / (n+1)!n! = 2nCn / n+1

This is the nth Catalan number.

The Catalan numbers form a sequence of natural numbers that occur in various counting
problems.

The nth Catalan number is given directly in terms of binomial coefficients by

The first Catalan numbers for n = 0, 1, 2, 3, ... are

1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845,
35357670, 129644790, 477638700, 1767263190, 6564120420, 24466267020, 91482563640,
343059613650, 1289904147324, 4861946401452, ...

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 26


APPLICATIONS OF BINARY TREES

The following are the applications of binary trees:

1) Binary Search Tree: Used in many search applications that constantly shows and hides data,
such as data. For example, map and set objects in many libraries.

2) Binary Space Partition: Used in almost any 3D video game to determine which objects need
to be rendered.

3) Binary Tries: Used in almost every high-bandwidth router to store router tables.

4) Syntax Tree: Constructed by compilers and (implicit) calculators to parse expressions.

5) Hash Trees: Used in P2P programs and special image signatures that require a hash to be
validated, but the entire file is not available.

6) Heaps: Used to implement efficient priority queues and also used in heap sort.

7) Treap: Randomized data structure for wireless networks and memory allocation.

8) T-Tree: Although most databases use a form of B-tree to store data on the drive, databases
that store all (most) data often use T-trees.

9) Huffman Coding Tree (Chip Uni): Used in compression algorithms, eg. For example, in
.jpeg and .mp3.GGM Trees file formats - used in cryptographic applications to generate a tree
with pseudo-random numbers.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 27


BINARY SEARCH TREES

A binary search tree (BST) is a binary tree with the following properties:

 All items in the left sub-tree are less than the root.
 All items in the right sub-tree are greater than or equal to the root.
 Each sub-tree is itself a binary search tree.

Example:

Valid Binary Search Trees

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 28


Invalid Binary Search Trees

Operations on Binary Search Trees using Arrays

Inserting a new element into the Binary Search Tree using Arrays

Inserting data into a binary search tree is much simpler. All we need to do is follow the branches
to an empty sub-tree and then insert the new node. All BST insertions take place at a leaf or a
leaf like node that is a node that has only one null sub-tree.

BSTInsertion

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 29


Algorithm insertBST(tree, item, Left, Right, value)

1) If (tree!== null)

2) If (item < tree[value])

tree[left]=insertBST[item, tree[left]);

else

3) If (item > tree[value])

tree[right]=insertBST[item, tree[right]);

Return 1;

} // end of insertBST

Deleting a element from the Binary Search Tree using Arrays

To delete a node from a binary search tree, we must first locate it. There are four possible cases
when we delete a node.

1) The node has no children.


2) The node has only a right sub-tree.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 30


3) The node has only a left sub-tree.
4) The node has two sub-trees.

The node has only a right sub-tree

 Delete the node


 Attach the right sub-tree to the deleted node’s parent.

The node has only a left sub-tree

 Delete the node


 Attach the left sub-tree to the deleted node’s parent.

The node has two sub-trees.

 Find the largest node in the deleted node’s left sub-tree and move its data to
replace the deleted node’s data or
 Find the smallest node in the deleted node’s right sub-tree and move its data to
replace the deleted node’s data.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 31


Algorithm deleteBST(tree, Left, Right, Item, value)

1) If (tree == null)

Return 0;

2) If (item< tree[value])

tree[left]=deleteBST (root[left],item);

else

3) If (item> tree[value])

tree[right]=deleteBST (root[right],item);

else

4) // Delete node with two children

if ( tree[left] == NULL)&& ( tree[right] == NULL)

temp= FindMin(root[right]);

tree[value] = tempvalue;

tree[right] = deleteBST(tree[value], root[right]);

free(temp);

Return 1;

else

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 32


5) // Delete node with one child or zero child

temp=tree;

6) if(tree[left]==NULL) then

tree = tree[right];

else

7) if(tree[right]==NULL) then

tree = tree[left];

free(temp);

Operations on Binary Search Trees using Linked lists

Binary Search Tree Type Definitions

typedef struct node

void *element;

struct node *left;

struct node *right;

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 33


}NODE;

typedef struct

int count;

NODE * root;

}BST_TREE;

Creating a Binary Search tree

Algorithm CreateBinarySearchtree(TREE * tree)

// This algorithm dynamically allocates memory for a node and creates the head structure for the
tree.

// Local declarations

int data;

1) // Check whether the tree is empty

if(TREECOUNT=0)

tree = (TREE*tree)malloc(sizeof(TREE*tree)

tree->data = data;

2) // Set the left child link to null

tree->left = NULL;

3) // Set the right child link to null

tree ->right = NULL;

4) return(tree); }

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 34


Inserting a new node into the Binary Search Tree using Linked lists

Algorithm insertBST(BST_TREE *root, void *Pnew)

1) If (root == null)

root = Pnew;

else

2) current = root;

3) While (current != null)

parent = current;

4) If (Pnew key < current key)

current = currentleft;

else

5) current = current right;

// Location for new node found

6) If (Pnew key < parent key)

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 35


parentleft = Pnew;

else

7) parentright = Pnew;

8) (TREECOUNT)++;

Return(tree);

} // end of insertBST

Deleting a node from the Binary Search Tree using Linked lists

Algorithm deleteBST(BST_TREE *root, void* value, int x)

1) If (root == null)

Return 0;

2) If (x < root value)

return deleteBST (root left, x)

else

3) if (x > root value)

return deleteBST (root right, x)

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 36


else

4) // Delete node with two children

if ( root left == NULL)&& ( root right == NULL)

temp= FindMin(rootright);

rootvalue = tempvalue;

treeright = deleteBST(rootvalue, rootright);

free(temp);

Return 1;

else

5) // Delete node with one child or zero child

temp=root;

6) if(rootleft==NULL) then

root = rootright;

else

7) if(rootright==NULL) then

root = rootleft;

free(temp);

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 37


8) (TREECOUNT)--;

9) return(root); }

ADVANCED TREES, FORESTS AND ORCHARDS

AVL TREES (Adelson – Velskill and Landis)

An AVL tree is a Binary Search tree in which the heights of the sub-trees differ by no more than
one and every sub-tree is an AVL tree.

An AVL tree is a Height-balanced binary search tree. The balance factor for any node in an AVL
tree must be +1, 0, or -1.

The descriptive identifiers, LH for left high(+1) to indicate that the left sub-tree is higher than the
right sub-tree, EH for even high(0) to indicate that the sub-trees are the same height, and RH for
right high(-1) to indicate that the left sub-tree is shorter than the right sub-tree.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 38


Balancing AVL trees

Balancing AVL trees is done by rotating nodes either to the left or to the right.

All unbalanced trees fall into one of these four cases.

1) Left of left(Rotate Right)


2) Right of right(Rotate Left)
3) Right of left(Double rotation)
4) Left of right(Double rotation)

Left of left(Rotate Right)

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 39


When the out of balance condition has been created by a left-high sub-tree of a left-high tree, we
must balance the tree by rotating the out-of-balance node to the right.

Right of right(Rotate Left)

When the out of balance condition has been created by a right-high sub-tree of a right-high tree,
we must balance the tree by rotating the out-of-balance node to the left.

3) Right of left (Double rotation)

The first two cases required single rotations to balance the trees. In this case we need to rotate
two nodes, one to the left and one to the right, to balance the tree.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 40


In this case we see an out-of-balance tree in which the root is left high and the left sub-tree is
right high. To balance this tree, we first rotate the left sub-tree to the left, then we rotate the root
to the right making the left node the new root.

4) Left of right (Double rotation)

To balance the tree, we first rotate the right sub-tree and then rotate the root left. Because the
out-of-balance condition is created by a right-high sub-tree on a right-high branch, we must
double rotate. We begin by rotating the right sub-tree to the right, we then rotate the root left,
which gives us the balanced tree.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 41


Operations on AVL trees using Arrays

Inserting a new element into an AVL Tree using Arrays

Whenever a new node is inserted into the AVL tree, an out of balance in heights will arise in
either of the sub-trees. We have to perform the rotations to balance the heights of the sub-trees.

Algorithm AVLTreeInsert(tree, int X, int Height)

1) if (tree== NULL)

tree[data] = X;

tree[left]=NULL;

tree[right]= NULL;

else
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 42
2) if (X < tree[data])

tree[Left]= AVLTreeInsert(tree[Left], X);

if(Height(tree[Left]) – (Height(tree[Right]) == 2)

if (X < tree[data])

tree = Single Rotation with left(tree);

else

tree = Double Rotation with left(tree);

3) if (X > tree[data])

tree[Right]= AVLTreeInsert(tree[Right], X);

if(Height(treeLeft) – (Height(treeRight) == 2)

if (X > tree[data])

tree = Single Rotation with right(tree);

else

tree = Double Rotation with right(tree);

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 43


4) tree[Height] = Max(Height(tree[Left]),Height(tree[Right]) ) +1;

} end of insert AVL tree

Algorithm SingleRotatewithLeft(Position K2)

Position K1;

K1 = K2 [Left];

K2 [Left] = K2[Right];

K1[Right] = K2;

K2 [Height] = Max(Height(K2[Left]),Height(K2[Right]) ) +1;

K1 [Height] = Max(Height(K1[Left]),Height(K1[Right]) ) +1;

return K1;

Algorithm DoubleRotatewithLeft(Position K3)

1) // Rotate between K1 and K2

K3 [Left] = Single Rotate with Right(K3 [Left]);

2) // Rotation between K3 & K2

Return Single Rotate with Left(K3);

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 44


}

Algorithm SingleRotatewithRight(Position K1)

Position K2;

K2 = K1[Right];

K1[Right] = K2[Left];

K2 [Left]= K1;

K2 [Height] = Max(Height(K2[Left]),Height(K2[Right]) ) +1;

K1[Height] = Max(Height(K1[Left]),Height(K1[Right]) ) +1;

return K2;

Algorithm DoubleRotatewithRight(Position K1)

1) // Rotate between K2 and K3

K1[Right] = Single Rotate with Left(K1[Right]);

2) // Rotation between K1 & K2

Return Single Rotate with Right(K1);

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 45


Deleting an element from an AVL Tree using Arrays

To delete a node from an AVL list, we need to determine if it is a leaf or leaf like node. If a node
has two sub-trees, we must search for a Left sub-tree for its largest node. When we find it, we
move its data to replace the deleted data and then recursively call the delete function to delete a
valid leaf node.

We must search for a Right sub-tree for its smallest node. When we find it, we move its data to
replace the deleted data and then recursively call the delete function to delete a valid leaf node.

Delete Right balance is used when a delete has occurred on a left sub-tree and the tree needs to
be rebalanced. We need to rebalance only if the root is right-high.

Delete Left balance is used when a delete has occurred on a right sub-tree and the tree needs to
be rebalanced. We need to rebalance only if the root is left high.

Because the out-of-balance condition is created by a left-high sub-tree on a right-high Branch,


we must double rotate. We begin by rotating the right sub-tree to the right, we then rotate the
root left, which gives us the balanced tree.(left-of-right).

In this case we see an out-of-balance tree in which the root is left high and the left sub-tree is
right high. To balance this tree, we first rotate the left sub-tree to the left, and then we rotate the
root to the right making the left node the new root (right-of-left).

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 46


Algorithm AVLTreeDelete(tree, int X, int Height)

1) if (tree!= NULL)

if (X < tree[data])

tree[Left] = AVLTreeDelete(X, tree[Left]);

if(Height(tree[Left]) – (Height(tree[Right]) == 2)

if (X < tree[data])

tree = Single Rotation with left(tree);

else

tree = Double Rotation with left(tree);

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 47


}

3) if (X > tree[data])

tree[Right] = AVLTreeDelete(X, tree[Right]);

if(Height(tree[Left]) – (Height(tree[Right]) == 2)

if (X > tree[data])

tree = Single Rotation with right(tree);

else

tree = Double Rotation with right(tree);

4) tree[Height]= Max(Height(tree[Left]),Height(tree[Right]) ) +1;

Algorithm SingleRotatewithLeft(Position K2)

Position K1;

K1 = K2 [Left];

K2 [Left] = K2[Right];

K1[Right] = K2;

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 48


K2 [Height] = Max(Height(K2[Left]),Height(K2[Right]) ) +1;

K1 [Height] = Max(Height(K1[Left]),Height(K1[Right]) ) +1;

return K1;

Algorithm DoubleRotatewithLeft(Position K3)

1) // Rotate between K1 and K2

K3 [Left] = Single Rotate with Right(K3 [Left]);

2) // Rotation between K3 & K2

Return Single Rotate with Left(K3);

Algorithm SingleRotatewithRight(Position K1)

Position K2;

K2 = K1[Right];

K1[Right] = K2[Left];

K2 [Left]= K1;

K2 [Height] = Max(Height(K2[Left]),Height(K2[Right]) ) +1;

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 49


K1[Height] = Max(Height(K1[Left]),Height(K1[Right]) ) +1;

return K2;

Algorithm DoubleRotatewithRight(Position K1)

1) // Rotate between K2 and K3

K1[Right] = Single Rotate with Left(K1[Right]);

2) // Rotation between K1 & K2

Return Single Rotate with Right(K1); }

Operations on AVL trees using Linked lists

AVL Tree Type Definitions

typedef struct {

int key;

int data;

struct node *left;

struct node *right;

int bal ;

}NODE;

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 50


typedef struct

int count;

NODE * root;

} AVL_ TREE;

Creating an AVL tree

Algorithm AVL_Create(tree)

AVL_TREE * tree

tree = (AVL_TREE * tree) malloc(sizeof(AVL_TREE*tree));

if (tree)

tree  root = NULL;

tree  count = 0;

Return(tree); }

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 51


Inserting a new node into an AVL Tree using Linked lists

Algorithm AVLTreeInsert(AVL_TREE tree, int X)

1) if (tree== NULL)

tree=(AVL_TREE *tree)malloc(sizeof(AVL_TREE *tree)));

tree  data = X;

tree Height = 0;

tree left=NULL;

tree right =NULL;

else

2) if (X < tree data)

treeLeft = AVLTreeInsert(treeLeft, X);

if(Height(treeLeft) – (Height(treeRight) == 2)

if (X < tree data)

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 52


tree = Single Rotation with left(tree);

else

tree = Double Rotation with left(tree);

3) if (X > tree data)

treeRight = AVLTreeInsert(treeRight, X);

if(Height(treeLeft) – (Height(treeRight) == 2)

if (X > tree data)

tree = Single Rotation with right(tree);

else

tree = Double Rotation with right(tree);

4) treeHeight = Max(Height(treeLeft),Height(treeRight) ) +1;

5) (TREECOUNT)++;

return(tree);

} end of insert AVL tree

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 53


Algorithm SingleRotatewithLeft(Position K2)

Position K1;

K1 = K2 Left;

K2 Left = K2 Right;

K1 Right = K2;

K2 Height = Max(Height(K2Left),Height(K2Right) ) +1;

K1 Height = Max(Height(K1Left),Height(K1Right) ) +1;

return K1;

Algorithm DoubleRotatewithLeft(Position K3)

1) // Rotate between K1 and K2

K3 Left = Single Rotate with Right(K3 Left);

2) // Rotation between K3 & K2

Return Single Rotate with Left(K3);

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 54


Algorithm SingleRotatewithRight(Position K1)

Position K2;

K2 = K1 Right;

K1 Right = K2 Left;

K2 Left= K1;

K2 Height = Max(Height(K2Left),Height(K2Right) ) +1;

K1 Height = Max(Height(K1Left),Height(K1Right) ) +1;

return K2;

Algorithm DoubleRotatewithRight(Position K1)

1) // Rotate between K2 and K3

K1 Right = Single Rotate with Left(K1 Right);

2) // Rotation between K1 & K2

Return Single Rotate with Right(K1);

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 55


Deleting a node from an AVL Tree using Linked lists

Algorithm AVLTreeDelete(AVL_TREE tree, int X)

1) if (tree!= NULL)

if (X < tree data)

treeLeft = AVLTreeDelete(X, treeLeft);

if(Height(treeLeft) – (Height(treeRight) == 2)

if (X < tree data)

tree = Single Rotation with left(tree);

else

tree = Double Rotation with left(tree);

3) if (X > tree data)

treeRight = AVLTreeDelete(X, treeRight);

if(Height(treeLeft) – (Height(treeRight) == 2)

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 56


if (X > tree data)

tree = Single Rotation with right(tree);

else

tree = Double Rotation with right(tree);

4) treeHeight = Max(Height(treeLeft),Height(treeRight) ) +1;

5) (TREECOUNT)--;

return(tree);

Algorithm SingleRotatewithLeft(Position K2)

Position K1;

K1 = K2 Left;

K2 Left = K2 Right;

K1 Right = K2;

K2 Height = Max(Height(K2Left),Height(K2Right) ) +1;

K1 Height = Max(Height(K1Left),Height(K1Right) ) +1;

return K1; }

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 57


Algorithm DoubleRotatewithLeft(Position K3)

1) // Rotate between K1 and K2

K3 Left = Single Rotate with Right(K3 Left);

2) // Rotation between K3 & K2

Return Single Rotate with Left(K3);

Algorithm SingleRotatewithRight(Position K1)

Position K2;

K2 = K1 Right;

K1 Right = K2 Left;

K2 Left= K1;

K2 Height = Max(Height(K2Left),Height(K2Right) ) +1;

K1 Height = Max(Height(K1Left),Height(K1Right) ) +1;

return K2;

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 58


Algorithm DoubleRotatewithRight(Position K1)

1) // Rotate between K2 and K3

K1 Right = Single Rotate with Left(K1 Right);

2) // Rotation between K1 & K2

Return Single Rotate with Right(K1);

THREADED BINARY TREES

The idea of threaded binary trees is to make in-order traversal faster and do it without stack and
without recursion. A binary tree is made threaded by making all right child pointers that would
normally be NULL point to the in-order successor of the node (if it exists).

There are two types of threaded binary trees.


Single Threaded: Where a NULL right pointers is made to point to the in-order successor if
successor exists.
Example:

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 59


The dotted lines represent threads.

Representation of a single threaded node

typedef struct Node


{
int data;
Node *left, *right;
bool rightThread;
}
Since right pointer is used for two purposes, the boolean variable rightThread is used to indicate
whether right pointer points to right child or in-order successor. Similarly, we can add left
Thread for a double threaded binary tree.

Double Threaded: Where both left and right NULL pointers are made to point to in-order
predecessor and in-order successor respectively. The predecessor threads are useful for reverse
in-order traversal and post-order traversal. The threads are also useful for fast accessing
ancestors of a node.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 60


Operations on Threaded Binary trees
In-order Traversal using Threads

Algorithm void in-order(struct Node *root)


{
1) struct Node *cur = leftmost(root);
2) while (cur != NULL)
{
3) print("%d ", cur->data);
4) // If this node is a thread node, then go to in-order successor
if (cur->rightThread)
cur = cur->right;
else
// Else go to the leftmost child in right sub-tree
5) cur = leftmost(cur->right);
}
}
Algorithm struct Node* leftMost(struct Node *n)

// This algorithm is used to find leftmost node in a tree rooted with n

{
1) if (n == NULL)

return NULL;

2) while (n->left != NULL)

n = n->left;

return n;
}

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 61


Example:

Following diagram demonstrates in-order traversal using threads.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 62


Inserting a node into the Single threaded binary tree
Algorithm
1) To insert a node our first task is to find the place to insert the node.
2) Take current = root .
3) Start from the current and compare root.data with n.
4) Always keep track of parent node while moving left or right.
5) If current.data is greater than n that means we go to the left of the root, if after moving to left,
the current = null then we have found the place where we will insert the new node. Add the new
node to the left of parent node and make the right pointer points to parent node and rightThread =
true for new node.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 63


6) If current.data is smaller than n that means we need to go to the right of the root, while going
into the right sub-tree, check rightThread for current node, means right thread is provided and
points to the in order successor, if rightThread = false then and current reaches to null, just insert
the new node else if rightThread = true then we need to detach the right pointer.

DELETE A NODE FROM THREADED BINARY TREE

In deletion, first the key to be deleted is searched, and then there are different cases for deleting
the Node in which key is found.

Case A: Leaf Node need to be deleted

In BST, for deleting a leaf Node the left or right pointer of parent was set to NULL. Here instead
of setting the pointer to NULL it is made a thread.

If the leaf Node is to be deleted is left child of its parent then after deletion, left pointer of parent
should become a thread pointing to its predecessor of the parent Node after deletion.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 64


If the leaf Node to be deleted is right child of its parent then after deletion, right pointer of parent
should become a thread pointing to its successor. The Node which was in-order successor of the
leaf Node before deletion will become the in-order successor of the parent Node after deletion.

struct Node *caseA(struct Node *root, struct Node *par, struct Node *ptr)

// If Node to be deleted is root

1) if (par == NULL)

root = NULL;

2) // If Node to be deleted is left of its parent

else if (ptr == par->left)

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 65


{

par->lthread = true;

par->left = ptr->left;

else

par->rthread = true;

par->right = ptr->right;

3) // Free memory and return new root

free(ptr);

return root;

Case B: Node to be deleted has only one child

After deleting the Node as in a BST, the in-order successor and in-order predecessor of the Node
are found out.

If Node to be deleted has left sub-tree, then after deletion right thread of its predecessor should
point to its successor.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 66


Before deletion 15 is predecessor and 2 is successor of 16. After deletion of 16, the Node 20
becomes the successor of 15, so right thread of 15 will point to 20.

If Node to be deleted has right sub-tree, then after deletion left thread of its successor should
point to its predecessor.

struct Node *caseB(struct Node *root, struct Node *par, struct Node *ptr)

struct Node *child;

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 67


1) // Initialize child Node to be deleted has left child.

if (ptr->lthread == false)

child = ptr->left;

// Node to be deleted has right child.

else

child = ptr->right;

2) // Node to be deleted is root Node.

if (par == NULL)

root = child;

// Node is left child of its parent.

else if (ptr == par->left)

par->left = child;

else

par->right = child;

3) // Find successor and predecessor

Node *s = inSucc(ptr);

Node *p = inPred(ptr);

4) // If ptr has left subtree.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 68


if (ptr->lthread == false)

p->right = s;

// If ptr has right subtree.

else

if (ptr->rthread == false)

s->left = p;

free(ptr);

return root;

Case C: Node to be deleted has two children

We find in-order successor of Node ptr (Node to be deleted) and then copy the information of
this successor into Node ptr. After this in-order successor Node is deleted using either Case A or
Case B.

struct Node *caseC(struct Node *root, struct Node *par, struct Node *ptr)

1) // Find inorder successor and its parent.

struct Node *parsucc = ptr;

struct Node *succ = ptr -> right;

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 69


2) // Find leftmost child of successor

while (succ->left != NULL)

parsucc = succ;

succ = succ -> left;

3) ptr->info = succ->info;

4) if (succ->lthread == true && succ->rthread == true)

root = caseA(root, parsucc, succ);

else

root = caseB(root, parsucc, succ);

return root;

FORESTS AND ORCHADS

Forest

A collection of disjoint trees is called a forest.

Creating forest from a tree

We can create a forest by cutting the root of a tree.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 70


There is a standard term for an arbitrary set of trees which is called a forest. In other words, you
can say a general tree as the root of a forest, and a forest is an ordered combination of zero or
more general trees.

Convert forest to binary tree

The forest is composed of several trees. The root node of each tree in the forest can be regarded
as a brother. Since each tree can be converted into a binary tree, the forest can also be converted
into a binary tree.

The steps to convert a forest into a binary tree are:

(1) First convert each tree to a binary tree;

(2) The first binary tree does not move, starting from the second binary tree, and sequentially
taking the root node of the latter binary tree as the front The right child node of the root node of a
binary tree is connected with a line. The binary tree obtained when all the binary trees are
connected is the binary tree converted from the forest.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 71


An orchard O is either empty set f or consists of an ordered tree T, called the first tree of the
orchard, together with another orchard O’ which contains the remaining trees of the orchard. We
may denote orchard with the ordered pair:

O = (T,O’)

Rotations

Rotation is the transformation from orchard to binary tree.

1. Draw the orchard so that the first child of each vertex is immediately below the vertex, rather
than centering the children below the vertex.

2. Draw a vertical link from each vertex to its first child and draw a horizontal link from each
vertex to its next sibling.
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 72
3. Remove the remaining original links.

4. Rotate the diagram 450 clockwise so that the vertical links appear as left links and the
horizontal links as right links.

EXPRESSION TREES

 An expression is a sequence of tokens that follow prescribed rules.


 A token may be either an operand or an operator.
 An expression tree is a binary tree with the following properties:

• Each leaf is an operand.


• The root and internal nodes are operators.
• Sub-trees are sub-expressions, with the root being an operator.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 73


Problem: Given an infix expression a x (b+c) + d. Draw a binary tree for the given infix
expression.

Expression trees Traversals

• Infix traversal
• Postfix traversal
• Prefix traversal

Infix traversal

Algorithm Infix(tree)

// Print the Infix expression of a Expression tree.

1) If (tree not empty)

2) Print (open parenthesis)

3) Infix ( tree left sub-tree)

4) Print (tree-token)

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 74


5) Infix ( tree right sub-tree)

6) Print (close parenthesis)

} // End if

} // End if

} // End of Infix

Postfix traversal

Algorithm Postfix(tree)

// Print the Postfix expression of a Expression tree.

1) If (tree not empty)

2) Postfix ( tree left sub-tree)

3) Postfix ( tree right sub-tree)

4) Print (tree token)

} // End of if

} // End of Postfix

Prefix traversal

Algorithm Prefix(tree)

// Print the Prefix expression of a Expression tree.

1) If (tree not empty)

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 75


2) Print (tree token)

3) Prefix ( tree left sub-tree)

3) Prefix ( tree right sub-tree)

} // End of if

} // End of Prefix

MULTIWAY TREES

A multi-way tree is defined as a tree that can have more than two children. If a multi-way tree
can have maximum m children, then this tree is called as multi-way tree of order m (or an m-way
tree).

The nodes in an m-way tree will be made up of m-1 key fields and pointers to children.

Multi-way tree of order 5

An m-way search tree is a m-way tree in which following condition should be satisfied:

 Each node is associated with m children and m-1 key fields.


 The keys in each node are arranged in ascending order.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 76


 The key values in the first sub-tree are less than the key in the first entry; the key values
in the other sub-trees are all Greater than or equal to the key in their parent entry. i.e key1
<= key2 <= …key k.

2-3 TREES

A 2-3 tree is a search tree. However, it is very different from a binary search tree.

Properties of a 2-3 tree:

 Each node has either one value or two value


 A node with one value is either a leaf node or has exactly two children (non-null). Values
in left sub-tree < value in node < values in right sub-tree.
 A node with two values is either a leaf node or has exactly three children (non-null).
Values in left sub-tree < first value in node < values in middle sub-tree < second value in
node < value in right sub-tree.
 All leaf nodes are at the same level of the tree.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 77


INSERTION

 If the tree is empty, create a node and put value into the node.
 Otherwise find the leaf node where the value belongs.
 If the leaf node has only one value, put the new value into the node.
 If the leaf node has more than two values, split the node and promote the median of the
three values to parent.
 If the parent then has three values, continue to split and promote, forming a new root
node if necessary.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 78


Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 79
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 80
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 81
SEARCH

Base cases

 If T is empty, return False (key cannot be found in the tree).

 If current node contains data value which is equal to K, return True.

 If we reach the leaf-node and it doesn’t contain the required key value K, return False.
 if K < currentNode.leftVal, we explore the left sub-tree of the current node.

else

 if currentNode.leftVal < K < currentNode.rightVal, we explore the middle sub-tree of the


current node.

else

 if K > currentNode.rightVal, we explore the right sub-tree of the current node.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 82


Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 83
DELETION

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 84


Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 85
B-Trees

B-Tree is a self-balanced search tree in which every node contains multiple keys and has more
than two children.

Here, the number of keys in a node and number of children for a node depends on the order of B-
Tree. Every B-Tree has an order m.

B-Tree Properties

Property 1: All leaf nodes must be at same level.

Property 2: All nodes except root must have at least [m/2]-1 keys and maximum of m-1 keys.

Property 3: All non leaf nodes except root (i.e. all internal nodes) must have at least m/2
children.

Property 4: If the root node is a non leaf node, then it must have at least 2 children.

Property 5: A non leaf node with n-1 keys must have n number of children.

Property 6: All the key values in a node must be in Ascending Order.

Example

B-Tree of Order 4 contains a maximum of 3 key values in a node and maximum of 4 children for
a node.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 86


Operations on a B-Tree

The following operations are performed on a B-Tree...

 Search
 Insertion
 Deletion

Search Operation in B-Tree

The search operation in B-Tree is similar to the search operation in Binary Search Tree. In a
Binary search tree, the search process starts from the root node and we make a 2-way decision
every time (we go to either left subtree or right subtree). In B-Tree also search process starts
from the root node but here we make an n-way decision every time. Where 'n' is the total number
of children the node has. In a B-Tree, the search operation is performed with O(log n) time
complexity. The search operation is performed as follows...

Step 1: Read the search element from the user.

Step 2: Compare the search element with first key value of root node in the tree.

Step 3: If both are matched, then display "Given node is found!!!" and terminate the function

Step 4: If both are not matched, then check whether search element is smaller or larger than that
key value.

Step 5: If search element is smaller, then continue the search process in left subtree.

Step 6: If search element is larger, then compare the search element with next key value in the
same node and repeat steps 3, 4, 5 and 6 until we find the exact match or until the search element
is compared with last key value in the leaf node.

Step 7: If the last key value in the leaf node is also not matched then display "Element is not
found" and terminate the function.
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 87
Insertion Operation in B-Tree

In a B-Tree, a new element must be added only at the leaf node. That means, the new keyValue
is always attached to the leaf node only. The insertion operation is performed as follows:

Step 1: Check whether tree is Empty.

Step 2: If tree is Empty, then create a new node with new key value and insert it into the tree as a
root node.

Step 3: If tree is Not Empty, then find the suitable leaf node to which the new key value is added
using Binary Search Tree logic.

Step 4: If that leaf node has empty position, add the new key value to that leaf node in ascending
order of key value within the node.

Step 5: If that leaf node is already full, split that leaf node by sending middle value to its parent
node. Repeat the same until the sending value is fixed into a node.

Step 6: If the splitting is performed at root node then the middle value becomes new root node
for the tree and the height of the tree is increased by one.

Example

Construct a B-Tree of Order 3 by inserting numbers from 1 to 10.

Solution:

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 88


Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 89
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 90
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 91
Deletion operation in a B-Tree

Deleting an element on a B-tree consists of three main events: searching the node where the key
to be deleted exists, deleting the key and balancing the tree if required.

While deleting a tree, a condition called underflow may occur. Underflow occurs when a node
contains less than the minimum number of keys it should hold.

There are three main cases for deletion operation in a B tree.

Case I:

The key to be deleted lies in the leaf. There are two cases for it.

1. The deletion of the key does not violate the property of the minimum number of keys a node
should hold.

In the tree below, deleting 32 does not violate the above properties.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 92


2. The deletion of the key violates the property of the minimum number of keys a node should
hold. In this case, we borrow a key from its immediate neighboring sibling node in the order of
left to right.

First, visit the immediate left sibling. If the left sibling node has more than a minimum number
of keys, then borrow a key from this node.

Else, check to borrow from the immediate right sibling node.

In the tree below, deleting 31 results in the above condition. Let us borrow a key from the left
sibling node.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 93


If both the immediate sibling nodes already have a minimum number of keys, then merge the
node with either the left sibling node or the right sibling node. This merging is done through the
parent node.

Deleting 30 results in the above case.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 94


Case II:

If the key to be deleted lies in the internal node, the following cases occur.

The internal node, which is deleted, is replaced by an inorder predecessor if the left child has
more than the minimum number of keys.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 95


2. The internal node, which is deleted, is replaced by an inorder successor if the right child has
more than the minimum number of keys.

3. If either child has exactly a minimum number of keys then, merge the left and the right
children.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 96


After merging if the parent node has less than the minimum number of keys then, look for the
siblings as in Case I.

Case III:

In this case, the height of the tree shrinks. If the target key lies in an internal node, and the
deletion of the key leads to a fewer number of keys in the node (i.e. less than the minimum
required), then look for the inorder predecessor and the inorder successor. If both the children
contain a minimum number of keys then, borrowing cannot take place. This leads to Case II(3)
i.e. merging the children.

Again, look for the sibling to borrow a key. But, if the sibling also has only a minimum number
of keys then, merge the node with the sibling along with the parent. Arrange the children
accordingly (increasing order).

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 97


Time Complexity

Best case Time complexity: Θ(log n)

Average case Space complexity: Θ(n)

Worst case Space complexity: Θ(n)

B+ Trees

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 singly linked lists to make the
search queries more efficient.

B+ Tree are used to store the large amount of data which can not be stored in the main memory.
Due to the fact that, size of main memory is always limited, the 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.

The internal nodes of B+ tree are often called index nodes. A B+ tree of order 3 is shown in the
following figure.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 98


Advantages of B+ Tree

 Records can be fetched in equal number of disk accesses.


 Height of the tree remains balanced and less as compare to B tree.
 We can access the data stored in a B+ tree sequentially as well as directly.
 Keys are used for indexing.
 Faster search queries as the data is stored only on the leaf nodes.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 99


B Tree VS B+ Tree

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.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 100


Example:

Insert the value 195 into the B+ tree of order 5 shown in the following figure.

195 will be inserted in the right sub-tree of 120 after 190. Insert it at the desired position.

The node contains greater than the maximum number of elements i.e. 4, therefore split it and
place the median node up to the parent.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 101


Now, the index node contains 6 children and 5 keys which violates the B+ tree properties,
therefore we need to split it, shown as follows.

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.

Example

Delete the key 200 from the B+ Tree shown in the following figure.

200 is present in the right sub-tree of 190, after 195. Delete it.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 102


Merge the two nodes by using 195, 190, 154 and 129.

Now, element 120 is the single element present in the node which is violating the B+ Tree
properties. Therefore, we need to merge it by using 60, 78, 108 and 120.

Now, the height of B+ tree will be decreased by 1.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 103


HEAPS

Heap is a binary tree with special characteristics.

In a heap data structure, nodes are arranged based on their values. A heap data structure some-
times also called as Binary Heap.

There are two types of heap data structures and they are as follows:

 Max Heap
 Min Heap

Every heap data structure has the following properties.

Property #1 (Ordering): Nodes must be arranged in an order according to their values based on
Max heap or Min heap.

Property #2 (Structural): All levels in a heap must be full except the last level and all nodes must
be filled from left to right strictly.

BUILDING A HEAP

We can build a heap data structures in two ways using

 Max Heap

 Min Heap

Max Heap

Max heap is a specialized full binary tree in which every parent node contains greater or equal
value than its child nodes.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 104


Operations on Max Heap

The following operations are performed on a Max heap data structure.

 Finding Maximum
 Insertion
 Deletion

Finding Maximum Value

 Finding the node which has maximum value in a max heap is very simple.

 In a max heap, the root node has the maximum value than all other nodes. So, directly we
can display root node value as the maximum value in max heap.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 105


Insertion Operation

Step 1: Insert the newNode as last leaf from left to right.

Step 2: Compare newNode value with its Parent node.

Step 3: If newNode value is greater than its parent, then swap both of them.

Step 4: Repeat step 2 and step 3 until newNode value is less than its parent node (or) newNode
reaches to root.

Example:

Consider the above max heap. Insert a new node with value 85.

Step 1: Insert the newNode with value 85 as last leaf from left to right. That means newNode is
added as a right child of node with value 75. After adding max heap is as follows.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 106


Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 107
Here, newNode value (85) is smaller than its parent node value (89). So, we stop insertion
process. Finally, max heap after insertion of a new node with value 85 is as follows.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 108


Deletion Operation

Step 1: Swap the root node with last node in max heap.

Step 2: Delete last node.

Step 3: Now, compare root value with its left child value.

Step 4: If root value is smaller than its left child, then compare left child with its right sibling.
Else go to Step 6

Step 5: If left child value is larger than its right sibling, then swap root with left
child otherwise swap root with its right child.

Step 6: If root value is larger than its left child, then compare root value with its right
child value.

Step 7: If root value is smaller than its right child, then swap root with right child otherwise stop
the process.

Step 8: Repeat the same until root node fixes at its exact position.

Example

Consider the above max heap. Delete root node (90) from the max heap.

Step 1: Swap the root node (90) with last node 75 in max heap. After swapping max heap is as
follows.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 109


Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 110
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 111
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 112
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 113
Here, node with value 75 is larger than its left child (15) and it does not have right child. So we
stop the process. Finally, max heap after deleting root node (90) is as follows.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 114


MINHEAP

Min-Heap is where the value of the root node is less than or equal to either of its children.

For Input → 35 33 42 10 14 19 27 44 26 31

INSERTION

To build a min heap we:

 Create a new child node at the end of the heap(last level).

 Add the new key to that node (append it to the array).

 Move the child up until you reach the root node and the heap property is satisfied.

Example

We will insert the values 3,1,6,5,2 and 4 in our heap.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 115


First Insert 3 in root of the empty heap.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 116


Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 117
Swap the 6 and 4

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 118


DELETION

To remove/delete a root node in a min heap:

 Delete the root node.


 Move the key of the last child to root.
 Compare the parent node with its children.
 If the value of the parent is greater than child nodes, swap them, and repeat until the heap
property is satisfied.

Example

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 119


Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 120
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 121
Now the heap property holds true.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 122

You might also like