You are on page 1of 50

Data Structures

MODULE – 5
printf(“ TREES ”);
Introduction:
Data Structures such as arrays, linked list, stack, and queue are linear data structures that
store data sequentially. In order to perform any operation in a linear data structure, the time
complexity increases with the increase in the data size. So it is difficult to use linear data
structures for large amount of data. To overcome the problem we are going to use non
linear data structures such as trees.
Definition :
Trees are non linear data structure that can be represented in a hierarchical manner.
A tree contains a finite non-empty set of elements. Any two nodes in the tree are connected
with a relationship of parent-child. Every individual elements in a tree can have any
number of sub trees.
Tree Terminology:
Parent : a node is said to be parent node to all its child nodes.
Leaf : a node that has no child nodes.
Siblings : Two nodes are siblings if they are children to the same parent node.
Degree of node: Number of sub trees of a given node
Ex: Degree of A=3,E=2

Root : The basic node of all nodes in the tree. All operations on the tree are performed with passing root
node to the functions. The first or top data item in hierarchical arrangement.
Child : a successor node connected to a node is called child. A node in binary tree may have at most two
children.
Degree of a tree: maximum degree of a node in a tree
Ex: Degree of above tree is 3
Depth or Height: Maximum level number of a node+1
Ex: Depth of above tree is 3+1=4
Non-terminal node: Any node except root whose degree is not zero .
Forest: Set of disjoint trees
Internal nodes: All nodes those have children nodes are called as internal nodes.
Path: Sequence of consecutive edges from the source node to the destination node
Applications :
1. Store hierarchical data, like folder structure, organization structure, XML/HTML data.
2. Binary Search Tree is a tree that allows fast search, insert, delete on a sorted data. It also allows
finding closest item
3. Trees can be used to represent real-world constructions like sentences or mathematical
expressions.
4. A tree is used to represent a file system.
Binary Tree:
A binary tree is a tree like structure that is rooted and in which each node has at
most two children and each child of a node is designated as its left or right child.
In this the maximum degree of any node is at most 2.
Number of nodes on each level i of binary tree is at most 2 power i
We can create binary tree using double linked list
Types of Binary Tree:
Complete Binary Tree: If all levels of tree are completely filled except the last level and the last level
has all keys as left as possible, is said to be a Complete Binary Tree.
Complete binary tree is also called as Perfect Binary Tree.
In a complete binary tree, every internal node has exactly two children and all leaf nodes are at same
level.
For example, at Level 2, there must be 22 = 4 nodes and at Level 3 there must be 23 = 8 nodes.
Fully Binary Tree: If every non terminal node in a binary tree consist of non empty
left sub tree and right sub tree. In other words if any node of a binary tree has either 0
or 2 child nodes then such tree is know as Fully binary tree . Fully binary tree also
know as strictly binary tree. Full binary tree is used to represent mathematical
expressions.
Skewed Binary Tree
If a tree which is dominated by left child node or right child node, is said to be a Skewed
Binary Tree.
In a skewed binary tree, all nodes except one have only one child node. The remaining node
has no child.
In a left skewed tree, most of the nodes have the left child without corresponding right child.
In a right skewed  tree, most of the nodes have the right child without corresponding left
child.
Binary Search tree: can be defined as a class of binary trees, in which the nodes are arranged
in a specific order. This is also called ordered binary tree.
In a binary search tree, the value of all the nodes in the left sub-tree is less than the value of the
root.
Similarly, value of all the nodes in the right sub-tree is greater than or equal to the value of the
root.
This rule will be recursively applied to all the left and right sub-trees of the root.
Example:
Construct the BST for the given numbers13, 3, 4, 12, 14, 10, 5, 1, 8, 2, 7, 9, 11, 6, 18 
Binary Tree Representation:

We can represent in two ways


1. Array representation:
In array representation of a binary tree, we use one-dimensional array (1-D Array) to
represent a binary tree.

To represent a binary tree of depth 'n' using array representation, we need one dimensional array with a
maximum size of 2n + 1.
If the parent at location i then left child at 2i+1 and right child 2i+2
2. Linked Representation:
We use a double linked list to represent a binary tree. In a double linked list, every node consists of
three fields. First field for storing left child address, second for storing actual data and third for
storing right child address.
Operations on Binary Search Tree:
1. Insertion
2. Deletion
3. Search
4. Inorder Traversal
5. Preorder Traversal
6. Postorder Traversal
Inorder Traversal:
In this traversal method, the left subtree is visited first, then the root and later the right sub-tree.
We should always remember that every node may represent a subtree itself.
If a binary tree is traversed in-order, the output will produce sorted key values in an ascending
order.

LDR(Left-Data-Right)

D→B→E→A→F→C→G
Preorder Traversal:
In this traversal method, the root node is visited first, then the left subtree and finally the right
subtree.

DLR(Data-left-right)

A→B→D→E→C→F→G
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.
LRD(Left-Right-Data)

D→E→B→F→G→C→A
Example :
Construct the Binary Search Tree and traversal
1) 25,36,20,40,22,10,5,12,28,38,48

2) 56,32,59,12,34,23,90,46,29,13
Example:

with the following construct the postorder


Inorder : 4, 2, 5, 1, 3, 6
Preorder: 1, 2, 4, 5, 3, 6

2. Inorder : 26,32,35,56,58,59,66
Preorder: 56,32,26,35,59,58,66

56
32 59

26 35 58 66
Binary Search Tree Implementation:
#include <stdio.h>
struct node* find_minimum(struct node *root)
#include <stdlib.h>
{
struct node
if(root == NULL)
{
return NULL;
int data;
else if(root->left != NULL)
struct node *right;
return find_minimum(root->left);
struct node *left;
return root;
};
}
struct node* search(struct node *root, int x)
{
if(root==NULL || root->data==x)
return root;
else if(x>root->data)
return search(root->right, x);
else
return search(root->left ,x);
}
struct node* new_node(int x) struct node* delete(struct node *root, int x)
{ {
struct node *p; if(root==NULL)
p = (struct node*)malloc(sizeof(struct node)); return NULL;
p->data = x; if (x>root->data)
p->left = NULL; root->right = delete(root->right, x);
p->right = NULL; else if(x<root->data)
  root->left = delete(root->left, x);
return p; else
} {
struct node* insert(struct node *root, int x) //No Children
{ if(root->left==NULL && root->right==NULL)
if(root==NULL) {
return new_node(x); free(root);
else if(x>root->data) return NULL;
root->right = insert(root->right, x); }
else
root->left = insert(root->left ,x);
return root;
}
//One Child
else if(root->left==NULL || root->right==NULL)
{
struct node *temp;
if(root->left==NULL)
temp = root->right;
else
temp = root->left;
free(root);
return temp;
}
 
//Two Children
else
{
struct node *temp = find_minimum(root->right);
root->data = temp->data;
root->right = delete(root->right, temp->data);
}
}
return root;
}
 
void inorder(struct node *root) void preorder(struct node *root)
{ {
if(root!=NULL) if(root!=NULL)
{ {
inorder(root->left); printf(" %d ", root->data);
printf(" %d ", root->data); preorder(root->left);
inorder(root->right); preorder(root->right);
} }
} }

void postorder(struct node *root)


{
if(root!=NULL)
{
postorder(root->left);
postorder(root->right);
printf(" %d ", root->data);
 
}
}
int main()
case 3:printf(“\n preorder traversal:\n”);
{
preorder(root);
struct node *root,*t;
printf(“\n”);break;
int ch,x,a;
case 4: printf(“\n postorder traversal:\n”);
printf(“\n enter the data to insert:”);
postorder(root);
scanf(“%d”,&x);
printf(“\n”);break;
root = new_node(x);
case 5:printf(“\n deletion:\n”);
Printf(“\n 1.Insertion\n2.inorder\n3.preorder
printf(“\n enter the element to be
\n4.postorder
delete:”);
while(1)
scanf(“%d”,&a);
{
root = delete(root, a);break;
printf(“\nEnter you choice”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:printf(“\nenter the data to insert:”);
scanf(“%d”,&x);
insert(root,x);break;
case 2:printf(“\n inorder traversal:\n”);
inorder(root);
printf("\n");break;
case 6: printf(“\n enter the element to search”);
scanf(“%d”,&x);
t= search(root,x);
if(t==NULL)
printf(“\n element not found!!!\n”);
else
printf(“\n Element found !!!\n”);
break;
case 7: exit(0);
}
}
return 0;
}
AVL Tree:
When in BST if we insert large data the size of the tree increases. If the size of the tree
increases then time complexity increases for the operation on BST. So, a need
arises to balance out the existing BST. Named after their inventor Adelson, Velski &
Landis, AVL trees are height balancing binary search tree. AVL tree checks the height of
the left and the right sub-trees and assures that the difference is 1,0,-1. This difference is
called the Balance Factor.
BalanceFactor = height(left-sutree) − height(right-sutree)
Example:
AVL Rotations :
If the difference in the height of left and right sub-trees is more than 1, the tree is balanced using
some rotation techniques.
To balance itself, an AVL tree may perform the following four kinds of rotations
Single Rotation:
Left rotation(LL)
Right rotation(RR)
Double Rotation:
Left-Right rotation(LR)
Right-Left rotation(RL)
Left Rotation:
If a tree becomes unbalanced, when a node is inserted into the right subtree of the right subtree, then we
perform a single left rotation
Right Rotation:
AVL tree may become unbalanced, if a node is inserted in the left subtree of the left subtree.
The tree then needs a right rotation.
Left-Right Rotation:
Double rotations are slightly complex version of already explained versions of rotations.
A left-right rotation is a combination of left rotation followed by right rotation.

A node has been inserted into the left subtree of the right subtree. This
makes C an unbalanced node. These scenarios cause AVL tree to
perform left-right rotation.

We first perform the left rotation on the left subtree of C. This
makes A, the left subtree of B.
Node C is still unbalanced, however now, it is because of the left-
subtree of the left-subtree.

We shall now right-rotate the tree, making B the new root node of this
subtree. C now becomes the right subtree of its own left subtree.

The tree is now balanced.


Right-Left Rotation:
It is a combination of right rotation followed by left rotation.

A node has been inserted into the right subtree of the left subtree. This
makes A, an unbalanced node with balance factor 2.

First, we perform the right rotation along C node, making C the


right subtree of its own left subtree B. Now, B becomes the right
subtree of A.
Node A is still unbalanced because of the right subtree of its
right subtree and requires a left rotation.

A left rotation is performed by making B the new root


node of the subtree. A becomes the left subtree of its
right subtree B.

The tree is now balanced.


Example:
Insert the following element
50 , 20 , 60 , 10 , 8 , 15 , 32 , 46 , 11 , 48

Start with 50

Consider next element 20


As 20 < 50, so insert 20 in 50’s left sub tree.

Consider next element 60


As 60 > 50, so insert 60 in 50’s right sub
tree.
Consider next element 10

As 10 < 50, so insert 10 in 50’s left sub tree.

As 10 < 20, so insert 10 in 20’s left sub tree.

Consider next element 8

As 8 < 50, so insert 8 in 50’s left sub tree.

As 8 < 20, so insert 8 in 20’s left sub tree.

As 8 < 10, so insert 8 in 10’s left sub tree.


To balance the tree,
Find the first imbalanced node on the path from the newly inserted node (node 8) to the root node.
The first imbalanced node is node 20.
Now, count three nodes from node 20 in the direction of leaf node.
Then, use AVL tree rotation to balance the tree.
Consider next element 15
As 15 < 50, so insert 15 in 50’s left sub tree.
As 15 > 10, so insert 15 in 10’s right sub tree.
As 15 < 20, so insert 15 in 20’s left sub tree.
To balance the tree,
Find the first imbalanced node on the path from the newly inserted node (node 15) to the root node.
The first imbalanced node is node 50.
Now, count three nodes from node 50 in the direction of leaf node.
Then, use AVL tree rotation to balance the tree.
Consider next element 32
As 32 > 20, so insert 32 in 20’s right sub tree.
As 32 < 50, so insert 32 in 50’s left sub tree.

Consider next element 46


As 46 > 20, so insert 46 in 20’s right sub tree.
As 46 < 50, so insert 46 in 50’s left sub tree.
As 46 > 32, so insert 46 in 32’s right sub tree.
Consider next element 11
As 11 < 20, so insert 11 in 20’s left sub tree.
As 11 > 10, so insert 11 in 10’s right sub tree.
As 11 < 15, so insert 11 in 15’s left sub tree.
Consider next element 48
As 48 > 20, so insert 48 in 20’s right sub tree.
As 48 < 50, so insert 48 in 50’s left sub tree.
As 48 > 32, so insert 48 in 32’s right sub tree.
As 48 > 46, so insert 48 in 46’s right sub tree.
To balance the tree,
Find the first imbalanced node on the path from the newly inserted node (node 48) to the root node.
The first imbalanced node is node 32.
Now, count three nodes from node 32 in the direction of leaf node.
Then, use AVL tree rotation to balance the tree.
B Tree:
B Tree is a specialized m-way tree that can be widely used for disk access. A B-Tree of order m can have at
most m-1 keys and m children. One of the main reason of using B-Tree is its capability to store large
number of keys in a single node and large key values by keeping the height of the tree relatively small.
A B-Tree of order m contains all the properties of an M way tree. In addition, it contains the following
properties.
Every node in a B-Tree contains at most m children.
Every node in a B-Tree except the root node and the leaf node contain at least m/2 children.
The root nodes must have at least 2 nodes.
All leaf nodes must be at the same level.
It is not necessary that, all the nodes contain the same number of children but, each node must have m/2
number of nodes.
A B -Tree of order 4 is
B-Tree Insertion
Create the B-Tree of order 5
key :- 1,12,8,2,25,6,14,28,17,7,52,16,48,68,3,26,29,53,55,45,67.

To construct order 5 we can give maximum 4 keys. we have


to arrange in ascending order
Consider 1

Consider 12
12>1 accommodate next

Consider 8,2,25
So maximum capacity is 4 need to split for that
consider center key i.e 8
Consider 6
Insert in left part of 8 6 is greater than 1 and 2 so after 2
after insert14,28,17,7,52,16,48,68,3,26,29,53,55,45,67.

You might also like