SlideShare a Scribd company logo
1 of 108
VELAMMAL ENGINEERING COLLEGE
An Autonomous Institution, Affiliated to Anna University Chennai, &
Approved by AICTE Delhi
Department of Computer Science and Engineering
UNIT III- NONLINEARDATASTRUCTURES–TREES
Dr.M.Usha, AP
AVL
Ms. Devi K
Assistant Professor
Velammal Engineering College
Chennai
VELAMMAL ENGINEERING COLLEGE
An Autonomous Institution, Affiliated to Anna University Chennai, & Approved by
AICTE Delhi
Problem behind the BST
 When the BST starting with the data: 10,20,30,40
10
20
30
40
10 20 30 40
It is similar to the normal linear search
AVL Tree
 Adelson-Velskii and Landis (AVL) trees
 self-balancing binary search trees.
 balancing factor of each node is either 0 or 1 or -1.
 Properties:
 Maximum possible number of nodes in AVL tree of height
H= 2H+1 – 1
AVL NODE DECLARATION
struct node
{
int data;
int h;
struct node *left , *right;
} *T=null;
typedef struct node *pos;
To retun Height of Pth node
int height(pos p)
{
if(p==NULL)
return -1;
else
return p->h;
}
To Calculate the height of the node t,
t->h=1+max(height(t->left),height(t->right));
Calculating Balancing Factor
 BF=height(t->right) - height(t->left)
 The balance factor (bf) of an AVL tree may take on one of the
values -1, 0, +1
Another Eg. to calculate BF,
Single Rotation With Left (Right
Rotation)
 Imbalance occur when inserting at Left of Left sub tree,
RR Routine
pos SRWL(pos k2)
{
pos k1;
k1=k2->left;
k2->left=k1->right;
k1->right=k2;
k2->h=1+max(height(k2->left),height(k2->right));
k1->h=1+max(height(k1->left),k2->h);
return k1;
}
Single Rotation With Right(Left Rotation)
 Imbalance occur when inserting data at Right of Right sub tree,
LR Routine
pos SRWR(pos k1)
{ pos k2;
k2=k1->right;
k1->right=k2->left;
k2->left=k1;
k1->h=1+max(height(k1->left),height(k1->right));
k2->h=1+max(k1->h,height(k2->right));
return k2;
}
Double Rotation With Left(Left-Right
Rotation)
 Imbalance occur when inserting data at Right of Lest sub tree,
LRR Routine
pos DRWL(pos k3)
{
k3->left=SRWR(k3->left);
return SRWL(k3);
}
Double Rotation With Right(Right-Left
Rotation)
 Imbalance occur when inserting data at Right of Lest sub tree,
RLR Routine
pos DRWR(pos k1)
{
k1->right=SRWL(k1->right);
return SRWR(k1);
}
Insert in AVL
pos insert(int x,pos t)
{
if(t==NULL)
{
t=(pos)malloc(sizeof(struct node));
t->data=x;
t->h=0;
t->left=t->right=NULL;
}
else if(x<t->data)
{
t->left=insert(x,t->left);
if(height(t->left)-height(t->right)==2)
{
if(x<t->left->data)
t=SRWL(t);
else
t=DRWL(t);
}
else if(x>t->data)
{
t->right=insert(x,t->right);
if(height(t->right)-height(t->left)==2)
{
if(x>t->right->data)
t=SRWR(t);
else
t=DRWR(t);
}
}
else
printf("element is in the tree already");
t->h=1+max(height(t->left),height(t->right));
return t;
}
CONTENTS
 1) Introduction to Trees.
 2) Basic terminologies
 3) Binary tree
 4) Binary tree types
 5) Binary tree representation
 6) Binary search tree
 7) Creation of a binary tree
 8) Operations on binary search tree Trees
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 18
Nonlinear Data Structures
 The data structure where data items are not organized
sequentially is called non linear data structure.
 A data item in a nonlinear data structure could be
attached to several other data elements to reflect a
special relationship among them and all the data items
cannot be traversed in a single run.
 Data structures like trees and graphs are some examples
of widely used nonlinear data structures.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 19
 A tree is a nonlinear hierarchical data structure that consists
of nodes connected by edges .
 It stores the information naturally in the form of hierarchical
style.
 In this, the data elements can be attached to more than one
element exhibiting the hierarchical relationship which
involves the relationship between the child, parent, and
grandparent.
 A tree can be empty with no nodes or a tree is a structure
consisting of one node called the root and zero or one or
more subtrees.
 In a general tree, A node can have any number of children
nodes but it can have only a single parent.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 20
TREE
Tree of species
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 21
BOOK AS TREE
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 22
CORPORATE TREE
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 23
XML DOM
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 24
TREE TERMINOLOGY
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 25
TREE TERMINOLOGIES
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 26
 1. Root-
 The first node from where the tree originates is called as a root node.
 In any tree, there must be only one root node.
 We can never have multiple root nodes in a tree data structure.
 2. Edge-
 The connecting link between any two nodes is called as an edge.
 In a tree with n number of nodes, there are exactly (n-1) number of edges.
 3. Parent-
 The node which has a branch from it to any other node is called as a parent node.
 In other words, the node which has one or more children is called as a parent node.
 In a tree, a parent node can have any number of child nodes.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 27
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 28
 4. Child-
 The node which is a descendant of some node is called as a child node.
 All the nodes except root node are child nodes.
 5. Siblings-
 Nodes which belong to the same parent are called as siblings.
 In other words, nodes with the same parent are sibling nodes.
 6. Degree-
 Degree of a node is the total number of children of that node.
 Degree of a tree is the highest degree of a node among all the nodes in the tree.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 29
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 30
 7. Internal Node-
 The node which has at least one child is called as an internal node.
 Internal nodes are also called as non-terminal nodes.
 Every non-leaf node is an internal node.
 8. Leaf Node-
 The node which does not have any child is called as a leaf node.
 Leaf nodes are also called as external nodes or terminal nodes.
 9. Level-
 In a tree, each step from top to bottom is called as level of a tree.
 The level count starts with 0 and increments by 1 at each level or step.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 31
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 32
 10. Height-
 Total number of edges that lies on the longest path from any leaf node to a
particular node is called as height of that node.
 Height of a tree is the height of root node.
 Height of all leaf nodes = 0
 11. Depth-
 Total number of edges from root node to a particular node is called as depth
of that node.
 Depth of a tree is the total number of edges from root node to a leaf node in
the longest path.
 Depth of the root node = 0
 The terms “level” and “depth” are used interchangeably.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 33
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 34
 12. Subtree-
 In a tree, each child from a node forms a subtree recursively.
 Every child node forms a subtree on its parent node.
 13. Forest-
 A forest is a set of disjoint trees.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 35
BINARY TREE
 Binary tree is a special tree data structure in which each node can have at most 2
children.
 Thus, in a binary tree,each node has either 0 child or 1 child or 2 children.
 Binary Tree Representation :
 1. Array Representation
 2. Linked Representation
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 36
Binary Tree using Array Representation
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 37
Cont..
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 38
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 39
Linked List Representation of Binary Tree
 Double linked list used 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.
 In this linked list representation, a
 node has the following structure...
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 40
struct node {
int data;
struct node *leftChild;
struct node *rightChild;
};
Types of Binary Trees-
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 41
 FULL BINARY TREE
 PERFECT BINARY TREE
 COMPLETE BINARY TREE
 SKEWED BINARY TREE
 1. Full / Strictly Binary Tree-

 A binary tree in which every node has either 0 or 2 children is called as a Full
binary tree.
 Full binary tree is also called as Strictly binary tree.
2.Perfect Binary Tree-

 A Perfect binary tree is a binary tree that satisfies the following 2 properties-
 Every internal node has exactly 2 children.
 All the leaf nodes are at the same level.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 42
 3.Complete Binary Tree-
 A complete binary tree is a binary tree that satisfies the following 2 properties-
 All the levels are completely filled except possibly the last level.
 The last level must be strictly filled from left to right.
 4.Skewed Binary Tree-
 A skewed binary tree is a binary tree that satisfies the following 2 properties-
 All the nodes except one node has one and only one child.
 The remaining node has no child.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 43
Properties of Binary Tree :
 1. A binary tree with n nodes has n+1 null branches.
 2. A tree with n nodes has exactly(n-1) edges.
 3. The maximum number of nodes at level i in a binary tree is, 2i where n> =0
 4. The maximum number of nodes in a perfect binary tree of height h is 2h+1 – 1 Nodes, where
h>=0.
 5. The maximum number of nodes in a complete binary of height h, has between 2h to 2h+1 –1,
h>=0.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 44
Binary Tree Traversals
 Displaying (or) visiting order of nodes in a binary tree is called as Binary Tree
Traversal.
 There are three types of binary tree traversals.
 In - Order Traversal
 Pre - Order Traversal
 Post - Order Traversal
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 45
1. Inorder Traversal
 Algorithm-
1. Traverse the left sub tree i.e. call Inorder (left sub tree)
2. Visit the root
3. Traverse the right sub tree i.e. call Inorder (right sub tree)
Left → Root → Right
 void inorder_traversal(struct node* root) {
 if(root != NULL) {
 inorder_traversal(root->leftChild);
 printf("%d ",root->data);
 inorder_traversal(root->rightChild);
 }
 }
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 46
Root
Root
NULL
2. Preorder Traversal
 Algorithm-
1. Visit the root
2. Traverse the left sub tree i.e. call Preorder (left sub tree)
3. Traverse the right sub tree i.e. call Preorder (right sub tree)
 Root → Left → Right
void pre_order_traversal(struct node* root) {
if(root != NULL) {
printf("%d ",root->data);
pre_order_traversal(root->leftChild);
pre_order_traversal(root->rightChild);
}
}
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 47
3. Postorder Traversal
 Algorithm-
 Traverse the left sub tree i.e. call Postorder (left sub tree)
 Traverse the right sub tree i.e. call Postorder (right sub tree)
 Visit the root
 Left → Right → Root
 void post_order_traversal(struct node* root) {
 if(root != NULL) {
 post_order_traversal(root->leftChild);
 post_order_traversal(root->rightChild);
 printf("%d ", root->data);
 }
 }
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 48
BINARY SEARCH TREE
 Binary Search Tree is a special kind of binary tree in which nodes
are arranged in a specific order.
 The left subtree of a node contains only nodes with keys lesser
than the node’s key.
 The right subtree of a node contains only nodes with keys greater
than the node’s key.
 The left and right subtree each must also be a binary search tree.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 49
Number of Binary Search Trees
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 50
Example-
Number of distinct binary search trees possible with 3 distinct keys
= 2×3C3 / 3+1
= 6C3 / 4
= 5
CONT..
 Create the binary search tree using the following data elements.
 43, 10, 79, 90, 12, 54, 11, 9, 50
 Insert 43 into the tree as the root of the tree.
 Read the next element, if it is lesser than the root node element, insert it as the root of
the left sub-tree.
 Otherwise, insert it as the root of the right of the right sub-tree.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 51
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 52
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 53
Operations on BST
 Insert an element – Delete an element – Search for an element – Find the
minimum/maximum element – Find the successor/predecessor of a node.
 Basic operations of a tree
 Search − Searches an element in a tree.
 FindMin – Find Minimum element in a tree
 FindMax – Find Maximum element in a tree
 Insert − Inserts an element in a tree.
 Delete − deletes an element in a tree.
 Pre-order Traversal − Traverses a tree in a pre-order manner.
 In-order Traversal − Traverses a tree in an in-order manner.
 Post-order Traversal − Traverses a tree in a post-order manner.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 54
1. Search Operation
 Search Operation is performed to search a particular element in the Binary Search Tree.
 Rules-
 For searching a given key in the BST,
 Compare the key with the value of root node.
 If the key is present at the root node, then return the root node.
 If the key is greater than the root node value, then recur for the root node’s right
subtree.
 If the key is smaller than the root node value, then recur for the root node’s left subtree.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 55
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 56
Algorithm:
Search (ROOT, ITEM)
•Step 1: IF ROOT -> DATA = ITEM OR
ROOT = NULL
Return ROOT
ELSE
IF ITEM < ROOT -> DATA
Return search(ROOT -> LEFT, ITEM)
ELSE
Return search(ROOT -> RIGHT,ITEM)
[END OF IF]
[END OF IF]
•Step 2: END
Example
 Consider key = 45 has to be searched in the given BST-
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 57
•We start our search from the root node 25.
•As 45 > 25, so we search in 25’s right subtree.
•As 45 < 50, so we search in 50’s left subtree.
•As 45 > 35, so we search in 35’s right subtree.
•As 45 > 44, so we search in 44’s right subtree but 44 has
no subtrees.
•So, we conclude that 45 is not present in the above BST.
2. Insertion Operation
 Rules-
 Insert function is used to add a new element in a binary search tree at appropriate
location. Insert function is to be designed in such a way that, it must node violate the
property of binary search tree at each value.
 Allocate the memory for tree.
 Set the data part to the value and set the left and right pointer of tree, point to NULL.
 If the item to be inserted, will be the first element of the tree, then the left and right of
this node will point to NULL.
 Else, check if the item is less than the root element of the tree, if this is true, then
recursively perform this operation with the left of the root.
 If this is false, then perform this operation recursively with the right sub-tree of the root.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 58
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 59
Insert (ROOT, ITEM)
•Step 1: IF ROOT = NULL
Allocate memory for TREE
SET ROOT -> DATA = ITEM
SET ROOT -> LEFT = ROOT -> RIGHT = NULL
ELSE
IF ITEM < ROOT -> DATA
Insert(ROOT -> LEFT, ITEM)
ELSE
Insert(ROOT -> RIGHT, ITEM)
[END OF IF]
[END OF IF]
•Step 2: END
struct node* insert(struct node* node, int
data)
{
/* If the tree is empty, return a new node */
if (node == NULL)
return newNode(data);
/* Recur down the tree */
if (data < node->data)
node->left = insert(node->left, data);
else if (data > node->data)
node->right = insert(node->right, data);
return node;
}
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 60
struct node *newNode(int item)
{
struct node *temp = (struct node
*)malloc(sizeof(struct node));
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
Example
 Consider the following example where key = 40 is inserted in the given BST-
We start searching for value 40 from the root node 100.
 As 40 < 100, so we search in 100’s left subtree.
 As 40 > 20, so we search in 20’s right subtree.
 As 40 > 30, so we add 40 to 30’s right subtree.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 61
FIND MIN
 Approch for finding minimum element:
 Traverse the node from root to left recursively until left is NULL.
 The node whose left is NULL is the node with minimum value.
int minValue(struct node* root)
{
struct node* current = root;
/* loop down to find the leftmost leaf */
while (current->left != NULL)
{
current = current->left;
}
return(current->key);
}
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 62
FIND MIN
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 63
FIND MAX
 Approch for finding maximum element:
 Traverse the node from root to right recursively until right is NULL.
 The node whose right is NULL is the node with maximum value.
 int maxValue(struct node* root)
 {
 struct node* current = root;
 /* loop down to find the leftmost leaf */
 while (current->right != NULL)
 {
 current = current->right;
 }
 return(current->key);
 } 3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 64
FIND MAX
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 65
Time Complexity:
 O(N) Worst case happens for left skewed trees in finding
the minimum value.
O(N) Worst case happens for right skewed trees in finding
the maximum value.
 O(1) Best case happens for left skewed trees in finding the
maximum value.
O(1) Best case happens for right skewed trees in finding the
minimum value.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 66
3. Deletion Operation
 Deletion Operation is performed to delete a particular
element from the Binary Search Tree.
• Case-01: Deletion Of A Node Having No Child (Leaf
Node)
• Case-02: Deletion Of A Node Having Only One
Child
• Case-02: Deletion Of A Node Having Two Children
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 67
Case-01: Deletion Of A Node Having No
Child (Leaf Node)
 It is the simplest case, in this case, replace the leaf node with the NULL and simple free the allocated
space.
 In the following image, we are deleting the node -4, since the node is a leaf node, therefore the node
will be replaced with NULL and allocated space will be freed.
 Example-Remove -4 from a BST.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 68
Case-02: Deletion Of A Node Having Only One
Child
 In this case, replace the node with its child and delete the child node, which now
contains the value which is to be deleted. Simply replace it with the NULL and free the
allocated space.
 Example :
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 69
Case-02: Deletion Of A Node Having Two
Children
 A node with two children may be deleted from the BST in the following two ways-
 Method-01:
 Visit to the right subtree of the deleting node.
 Pluck the least value element called as inorder successor.
 Replace the deleting element with its inorder successor.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 70
 struct node* delete_node(struct node*
root, int data)
 {
 if (root == NULL)
 return root;
 // If the key to be deleted is smaller than
the root's key,
 if (data < root->data)
 root->left = delete_node(root->left,
data);
 // If the key to be deleted is greater than
the root's key,
 else if (data > root->data)
 root->right = delete_node(root->right,
data);
 else
 {
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 71
// node with only one child or no child
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;
}
// node with two children:
struct node* temp = minValueNode(root->right);
// Copy the inorder successor's content to this node
root->data = temp->data;
// Delete the inorder successor
root->right = delete_node(root->right, temp->data);
}
return root;
}
 Algorithm
 Delete (ROOT, ITEM)
 Step 1: IF ROOT = NULL
Write "item not found in the tree"
// If the key to be deleted is smaller than the root's key,
then it lies in left subtree
ELSE IF ITEM < TREE -> DATA
Delete(ROOT->LEFT, ITEM)
// If the key to be deleted is greater than the root's key,
// then it lies in right subtree
ELSE IF ITEM > ROOT -> DATA
Delete(ROOT-> RIGHT, ITEM)
// node with two children: Get the inorder
predecessor(largest in the left subtree)
ELSE IF ROOT -> LEFT AND ROOT -> RIGHT
SET TEMP = findmax(TREE -> LEFT)
SET ROOT -> DATA = TEMP -> DATA
Delete(ROOT -> LEFT, TEMP -> DATA)
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 72
// node with only one child or no child
ELSE
SET TEMP = ROOT
IF ROOT -> LEFT = NULL AND ROOT->
RIGHT = NULL
SET ROOT = NULL
ELSE IF ROOT -> LEFT != NULL
SET ROOT = ROOT -> LEFT
ELSE
SET ROOT = ROOT -> RIGHT
[END OF IF]
FREE TEMP
[END OF IF]
Step 2: END
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 73
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 74
Example
 Consider the following example where node with value = 15 is deleted from
the BST-
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 75
Method-02:
 Visit to the left subtree of the deleting node.
 Pluck the greatest value element called as inorder predecessor.
 Replace the deleting element with its inorder predecessor.
 Consider the following example where node with value = 15 is deleted from the BST-
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 76
Advantages of using binary search tree
 Searching become very efficient in a binary search tree since, we
get a hint at each step, about which sub-tree contains the desired
element.
 The binary search tree is considered as efficient data structure in
compare to arrays and linked lists. In searching process, it
removes half sub-tree at every step. Searching for an element in a
binary search tree takes o(log2n) time. In worst case, the time it
takes to search an element is 0(n).
 It also speed up the insertion and deletion operations as compare
to that in array and linked list.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 77
TIME COMPLEXITY
 Time complexity of all BST Operations = O(h).
 Here, h = Height of binary search tree
 Worst Case-
 In worst case,
 The binary search tree is a skewed binary search tree.
 Height of the binary search tree becomes n.
 So, Time complexity of BST Operations = O(n).
 In this case, binary search tree is as good as unordered list with no benefits.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 78
 Best Case-
 In best case,
 The binary search tree is a balanced binary search tree.
 Height of the binary search tree becomes log(n).
 So, Time complexity of BST Operations = O(logn).
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 79
APPLICATIONS -BST
1) Used to express arithmetic expressions
2) Used to evaluate expression trees.
3) Used for indexing IP addresses.
4) It is used to implement dictionary.
5) It is used to implement multilevel indexing in DATABASE.
7) To implement Huffman Coding Algorithm.
8) It is used to implement searching Algorithm.
9) Implementing routing table in router.
3/5/2022
VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 80
What is a Tree?
 In CS a tree is
 an Organizational Structure for the storage and retrieval of data.
 Height balanced binary search trees: AVL trees, red-black trees
search faster than in an average binary search tree because the tree is guaranteed to have
the smallest possible depth.
 Another kind of multi-way search trees . Optimises search in external memory.
Two types of memory
 Main memory (RAM)
 External (peripheral) storage: hard disk,
CD-ROM, tape, etc.
Different considerations are important in designing algorithms and data
structures for primary (main) versus secondary (peripheral) memory.
BST
Binary Search Tree
Time Complexity : O(log(n))
Unbalanced Binary Search Tree
Time Complexity : O(n)
for search, insert and delete operations
What is the remedy??
 Remedy is self balancing trees.
 Automatically adjust to itself to get balanced.
 eg Red black tree
 B-Tree
What is B tree ?
 Intro
 Invented by Rudolf Bayer and Ed McCreight in 1972 at Boeing Research Labs.
 B-Tree is known as balanced m-way tree and used in external sorting.
 m-way node is were m=5 it describes that there should be m links and m-1 data.
 Algorithms and data structures for external memory as opposed to the main memory
B Tree
 A good example of a data structure for external memory is a B-tree.
 Better than binary search trees if data is stored in external memory (they are
NOT better with in-memory data!).
 Each node in a tree should correspond to a block of data.
 Each node stores many data items and has many successors (stores addresses
of successor blocks).
 The tree has fewer levels but search for an item involves more comparisons
at each level.
 There is a single root node, which may have only one record and two children
(or none if the tree is empty).
Properties of B tree
 Each node has a maximum of M children and minimum of
m/2 children
 Each node should have a fewer keys than children with a
maximum of m-1 keys
 Keys should be arranged in a defined order within the
node
 Key to be inserted into a fullnode, the node is splitted
B tree Example With Order m=4 & m=5
m=4
Maximum Children - 4
Minimum Children - Ceil (m/2) = 2
Maximum Keys - (m-1) =3
Min Keys - Ceil(m/2)-1 =1
m=5
Maximum Children - 5
Minimum Children - Ceil (m/2) = 3
Maximum Keys - (m-1) =4
Min Keys - Ceil(m/2)-1 =2
Operations on B trees
 Basic three opeartions
 Insertion
 Insertion will be done in the leaf nodes
 Deletion
 Search
Search for record with key 40:
Inserting 12:
Inserting 53:
Inserting 53: the node is too full!
Find the Middle Element
Splitting a node
Insertion with even order
 To insert elements in B tree element to be inserted is to be scanned from left
to right.
 If the order to construct an even order B tree then two sets of tree is created
Inserting in a B-Tree
 Find the node where the item is to be inserted by following the search
procedure.
 If the node is not full, insert the item into the node in order.
 If the node is full, it has to be split.
Example
 Construct a B-Tree of order 4 with
following set of datas
5,3,21,9,1,13,2,7,10,12,4,8
m=4 max keys=m-1 =3
5,3,21,9,1,13,2,7,10,12,4,8
m=4 max keys=m-1 =3
Deletion in B tree
 The key to be deleted is called the target key
Two Possibilities
 Target key can be a leaf node
 Target Key can be in internal node
Contd..
 Target key can be leaf node
Two Possibilities
 Leaf node contains more than min no of keys
 Leaf node contains min no of keys

Contd..
 If the target key is internal node

THANK YOU

More Related Content

What's hot

Data structure-questions
Data structure-questionsData structure-questions
Data structure-questions
Shekhar Chander
 

What's hot (20)

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
 
Review session2
Review session2Review session2
Review session2
 
Unit 4.1 (tree)
Unit 4.1 (tree)Unit 4.1 (tree)
Unit 4.1 (tree)
 
17. Trees and Graphs
17. Trees and Graphs17. Trees and Graphs
17. Trees and Graphs
 
Preparation Data Structures 10 trees
Preparation Data Structures 10 treesPreparation Data Structures 10 trees
Preparation Data Structures 10 trees
 
Preparation Data Structures 06 arrays representation
Preparation Data Structures 06 arrays representationPreparation Data Structures 06 arrays representation
Preparation Data Structures 06 arrays representation
 
Data structure-questions
Data structure-questionsData structure-questions
Data structure-questions
 
Chapter 9 ds
Chapter 9 dsChapter 9 ds
Chapter 9 ds
 
Tree and graph
Tree and graphTree and graph
Tree and graph
 
Unit 4.2(graphs)
Unit 4.2(graphs)Unit 4.2(graphs)
Unit 4.2(graphs)
 
Chapter 3 ds
Chapter 3 dsChapter 3 ds
Chapter 3 ds
 
Data structure-question-bank
Data structure-question-bankData structure-question-bank
Data structure-question-bank
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
 
THREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREETHREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREE
 
Normalisation by vmb
Normalisation by vmbNormalisation by vmb
Normalisation by vmb
 
Use of the Tree.
Use of the Tree.Use of the Tree.
Use of the Tree.
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 
Unsupervised learning clustering
Unsupervised learning clusteringUnsupervised learning clustering
Unsupervised learning clustering
 
Data Structures 5
Data Structures 5Data Structures 5
Data Structures 5
 
210 trees
210 trees210 trees
210 trees
 

Similar to Unit III - NON LINEAR DATA STRUCTURES

Final tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentationFinal tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentation
nakulvarshney371
 
Trees - Data structures in C/Java
Trees - Data structures in C/JavaTrees - Data structures in C/Java
Trees - Data structures in C/Java
geeksrik
 

Similar to Unit III - NON LINEAR DATA STRUCTURES (20)

DSA IV Unit.pptx
DSA IV Unit.pptxDSA IV Unit.pptx
DSA IV Unit.pptx
 
Tree
TreeTree
Tree
 
unit ii.pptx
unit ii.pptxunit ii.pptx
unit ii.pptx
 
Module 4.pptx
Module 4.pptxModule 4.pptx
Module 4.pptx
 
Trees in Data Structure
Trees in Data StructureTrees in Data Structure
Trees in Data Structure
 
UNIT-4 TREES.ppt
UNIT-4 TREES.pptUNIT-4 TREES.ppt
UNIT-4 TREES.ppt
 
Tree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanTree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal Khan
 
AD3251-Data Structures Design-Notes-Tree.pdf
AD3251-Data Structures  Design-Notes-Tree.pdfAD3251-Data Structures  Design-Notes-Tree.pdf
AD3251-Data Structures Design-Notes-Tree.pdf
 
Final tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentationFinal tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentation
 
Unit 3.ppt
Unit 3.pptUnit 3.ppt
Unit 3.ppt
 
Binary tree
Binary treeBinary tree
Binary tree
 
Chapter 8 ds
Chapter 8 dsChapter 8 ds
Chapter 8 ds
 
Trees - Data structures in C/Java
Trees - Data structures in C/JavaTrees - Data structures in C/Java
Trees - Data structures in C/Java
 
NON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptxNON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptx
 
Data structure tree - intermediate
Data structure tree - intermediateData structure tree - intermediate
Data structure tree - intermediate
 
DATA STUCTURES-TREES.pptx
DATA STUCTURES-TREES.pptxDATA STUCTURES-TREES.pptx
DATA STUCTURES-TREES.pptx
 
Mca admission in india
Mca admission in indiaMca admission in india
Mca admission in india
 
Dsc++ unit 3 notes
Dsc++ unit 3 notesDsc++ unit 3 notes
Dsc++ unit 3 notes
 
Unit II,III - Data Structures.pdf
Unit II,III - Data Structures.pdfUnit II,III - Data Structures.pdf
Unit II,III - Data Structures.pdf
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
 

Recently uploaded

AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spain
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 

Unit III - NON LINEAR DATA STRUCTURES

  • 1. VELAMMAL ENGINEERING COLLEGE An Autonomous Institution, Affiliated to Anna University Chennai, & Approved by AICTE Delhi Department of Computer Science and Engineering UNIT III- NONLINEARDATASTRUCTURES–TREES Dr.M.Usha, AP
  • 2. AVL Ms. Devi K Assistant Professor Velammal Engineering College Chennai VELAMMAL ENGINEERING COLLEGE An Autonomous Institution, Affiliated to Anna University Chennai, & Approved by AICTE Delhi
  • 3. Problem behind the BST  When the BST starting with the data: 10,20,30,40 10 20 30 40 10 20 30 40 It is similar to the normal linear search
  • 4. AVL Tree  Adelson-Velskii and Landis (AVL) trees  self-balancing binary search trees.  balancing factor of each node is either 0 or 1 or -1.  Properties:  Maximum possible number of nodes in AVL tree of height H= 2H+1 – 1
  • 5. AVL NODE DECLARATION struct node { int data; int h; struct node *left , *right; } *T=null; typedef struct node *pos;
  • 6. To retun Height of Pth node int height(pos p) { if(p==NULL) return -1; else return p->h; } To Calculate the height of the node t, t->h=1+max(height(t->left),height(t->right));
  • 7. Calculating Balancing Factor  BF=height(t->right) - height(t->left)  The balance factor (bf) of an AVL tree may take on one of the values -1, 0, +1
  • 8. Another Eg. to calculate BF,
  • 9. Single Rotation With Left (Right Rotation)  Imbalance occur when inserting at Left of Left sub tree,
  • 10. RR Routine pos SRWL(pos k2) { pos k1; k1=k2->left; k2->left=k1->right; k1->right=k2; k2->h=1+max(height(k2->left),height(k2->right)); k1->h=1+max(height(k1->left),k2->h); return k1; }
  • 11. Single Rotation With Right(Left Rotation)  Imbalance occur when inserting data at Right of Right sub tree,
  • 12. LR Routine pos SRWR(pos k1) { pos k2; k2=k1->right; k1->right=k2->left; k2->left=k1; k1->h=1+max(height(k1->left),height(k1->right)); k2->h=1+max(k1->h,height(k2->right)); return k2; }
  • 13. Double Rotation With Left(Left-Right Rotation)  Imbalance occur when inserting data at Right of Lest sub tree,
  • 14. LRR Routine pos DRWL(pos k3) { k3->left=SRWR(k3->left); return SRWL(k3); }
  • 15. Double Rotation With Right(Right-Left Rotation)  Imbalance occur when inserting data at Right of Lest sub tree,
  • 16. RLR Routine pos DRWR(pos k1) { k1->right=SRWL(k1->right); return SRWR(k1); }
  • 17. Insert in AVL pos insert(int x,pos t) { if(t==NULL) { t=(pos)malloc(sizeof(struct node)); t->data=x; t->h=0; t->left=t->right=NULL; } else if(x<t->data) { t->left=insert(x,t->left); if(height(t->left)-height(t->right)==2) { if(x<t->left->data) t=SRWL(t); else t=DRWL(t); } else if(x>t->data) { t->right=insert(x,t->right); if(height(t->right)-height(t->left)==2) { if(x>t->right->data) t=SRWR(t); else t=DRWR(t); } } else printf("element is in the tree already"); t->h=1+max(height(t->left),height(t->right)); return t; }
  • 18. CONTENTS  1) Introduction to Trees.  2) Basic terminologies  3) Binary tree  4) Binary tree types  5) Binary tree representation  6) Binary search tree  7) Creation of a binary tree  8) Operations on binary search tree Trees 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 18
  • 19. Nonlinear Data Structures  The data structure where data items are not organized sequentially is called non linear data structure.  A data item in a nonlinear data structure could be attached to several other data elements to reflect a special relationship among them and all the data items cannot be traversed in a single run.  Data structures like trees and graphs are some examples of widely used nonlinear data structures. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 19
  • 20.  A tree is a nonlinear hierarchical data structure that consists of nodes connected by edges .  It stores the information naturally in the form of hierarchical style.  In this, the data elements can be attached to more than one element exhibiting the hierarchical relationship which involves the relationship between the child, parent, and grandparent.  A tree can be empty with no nodes or a tree is a structure consisting of one node called the root and zero or one or more subtrees.  In a general tree, A node can have any number of children nodes but it can have only a single parent. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 20 TREE
  • 21. Tree of species 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 21
  • 22. BOOK AS TREE 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 22
  • 24. XML DOM 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 24
  • 27.  1. Root-  The first node from where the tree originates is called as a root node.  In any tree, there must be only one root node.  We can never have multiple root nodes in a tree data structure.  2. Edge-  The connecting link between any two nodes is called as an edge.  In a tree with n number of nodes, there are exactly (n-1) number of edges.  3. Parent-  The node which has a branch from it to any other node is called as a parent node.  In other words, the node which has one or more children is called as a parent node.  In a tree, a parent node can have any number of child nodes. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 27
  • 29.  4. Child-  The node which is a descendant of some node is called as a child node.  All the nodes except root node are child nodes.  5. Siblings-  Nodes which belong to the same parent are called as siblings.  In other words, nodes with the same parent are sibling nodes.  6. Degree-  Degree of a node is the total number of children of that node.  Degree of a tree is the highest degree of a node among all the nodes in the tree. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 29
  • 31.  7. Internal Node-  The node which has at least one child is called as an internal node.  Internal nodes are also called as non-terminal nodes.  Every non-leaf node is an internal node.  8. Leaf Node-  The node which does not have any child is called as a leaf node.  Leaf nodes are also called as external nodes or terminal nodes.  9. Level-  In a tree, each step from top to bottom is called as level of a tree.  The level count starts with 0 and increments by 1 at each level or step. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 31
  • 33.  10. Height-  Total number of edges that lies on the longest path from any leaf node to a particular node is called as height of that node.  Height of a tree is the height of root node.  Height of all leaf nodes = 0  11. Depth-  Total number of edges from root node to a particular node is called as depth of that node.  Depth of a tree is the total number of edges from root node to a leaf node in the longest path.  Depth of the root node = 0  The terms “level” and “depth” are used interchangeably. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 33
  • 35.  12. Subtree-  In a tree, each child from a node forms a subtree recursively.  Every child node forms a subtree on its parent node.  13. Forest-  A forest is a set of disjoint trees. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 35
  • 36. BINARY TREE  Binary tree is a special tree data structure in which each node can have at most 2 children.  Thus, in a binary tree,each node has either 0 child or 1 child or 2 children.  Binary Tree Representation :  1. Array Representation  2. Linked Representation 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 36
  • 37. Binary Tree using Array Representation 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 37
  • 40. Linked List Representation of Binary Tree  Double linked list used 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.  In this linked list representation, a  node has the following structure... 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 40 struct node { int data; struct node *leftChild; struct node *rightChild; };
  • 41. Types of Binary Trees- 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 41  FULL BINARY TREE  PERFECT BINARY TREE  COMPLETE BINARY TREE  SKEWED BINARY TREE
  • 42.  1. Full / Strictly Binary Tree-   A binary tree in which every node has either 0 or 2 children is called as a Full binary tree.  Full binary tree is also called as Strictly binary tree. 2.Perfect Binary Tree-   A Perfect binary tree is a binary tree that satisfies the following 2 properties-  Every internal node has exactly 2 children.  All the leaf nodes are at the same level. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 42
  • 43.  3.Complete Binary Tree-  A complete binary tree is a binary tree that satisfies the following 2 properties-  All the levels are completely filled except possibly the last level.  The last level must be strictly filled from left to right.  4.Skewed Binary Tree-  A skewed binary tree is a binary tree that satisfies the following 2 properties-  All the nodes except one node has one and only one child.  The remaining node has no child. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 43
  • 44. Properties of Binary Tree :  1. A binary tree with n nodes has n+1 null branches.  2. A tree with n nodes has exactly(n-1) edges.  3. The maximum number of nodes at level i in a binary tree is, 2i where n> =0  4. The maximum number of nodes in a perfect binary tree of height h is 2h+1 – 1 Nodes, where h>=0.  5. The maximum number of nodes in a complete binary of height h, has between 2h to 2h+1 –1, h>=0. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 44
  • 45. Binary Tree Traversals  Displaying (or) visiting order of nodes in a binary tree is called as Binary Tree Traversal.  There are three types of binary tree traversals.  In - Order Traversal  Pre - Order Traversal  Post - Order Traversal 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 45
  • 46. 1. Inorder Traversal  Algorithm- 1. Traverse the left sub tree i.e. call Inorder (left sub tree) 2. Visit the root 3. Traverse the right sub tree i.e. call Inorder (right sub tree) Left → Root → Right  void inorder_traversal(struct node* root) {  if(root != NULL) {  inorder_traversal(root->leftChild);  printf("%d ",root->data);  inorder_traversal(root->rightChild);  }  } 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 46 Root Root NULL
  • 47. 2. Preorder Traversal  Algorithm- 1. Visit the root 2. Traverse the left sub tree i.e. call Preorder (left sub tree) 3. Traverse the right sub tree i.e. call Preorder (right sub tree)  Root → Left → Right void pre_order_traversal(struct node* root) { if(root != NULL) { printf("%d ",root->data); pre_order_traversal(root->leftChild); pre_order_traversal(root->rightChild); } } 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 47
  • 48. 3. Postorder Traversal  Algorithm-  Traverse the left sub tree i.e. call Postorder (left sub tree)  Traverse the right sub tree i.e. call Postorder (right sub tree)  Visit the root  Left → Right → Root  void post_order_traversal(struct node* root) {  if(root != NULL) {  post_order_traversal(root->leftChild);  post_order_traversal(root->rightChild);  printf("%d ", root->data);  }  } 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 48
  • 49. BINARY SEARCH TREE  Binary Search Tree is a special kind of binary tree in which nodes are arranged in a specific order.  The left subtree of a node contains only nodes with keys lesser than the node’s key.  The right subtree of a node contains only nodes with keys greater than the node’s key.  The left and right subtree each must also be a binary search tree. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 49
  • 50. Number of Binary Search Trees 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 50 Example- Number of distinct binary search trees possible with 3 distinct keys = 2×3C3 / 3+1 = 6C3 / 4 = 5
  • 51. CONT..  Create the binary search tree using the following data elements.  43, 10, 79, 90, 12, 54, 11, 9, 50  Insert 43 into the tree as the root of the tree.  Read the next element, if it is lesser than the root node element, insert it as the root of the left sub-tree.  Otherwise, insert it as the root of the right of the right sub-tree. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 51
  • 54. Operations on BST  Insert an element – Delete an element – Search for an element – Find the minimum/maximum element – Find the successor/predecessor of a node.  Basic operations of a tree  Search − Searches an element in a tree.  FindMin – Find Minimum element in a tree  FindMax – Find Maximum element in a tree  Insert − Inserts an element in a tree.  Delete − deletes an element in a tree.  Pre-order Traversal − Traverses a tree in a pre-order manner.  In-order Traversal − Traverses a tree in an in-order manner.  Post-order Traversal − Traverses a tree in a post-order manner. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 54
  • 55. 1. Search Operation  Search Operation is performed to search a particular element in the Binary Search Tree.  Rules-  For searching a given key in the BST,  Compare the key with the value of root node.  If the key is present at the root node, then return the root node.  If the key is greater than the root node value, then recur for the root node’s right subtree.  If the key is smaller than the root node value, then recur for the root node’s left subtree. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 55
  • 56. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 56 Algorithm: Search (ROOT, ITEM) •Step 1: IF ROOT -> DATA = ITEM OR ROOT = NULL Return ROOT ELSE IF ITEM < ROOT -> DATA Return search(ROOT -> LEFT, ITEM) ELSE Return search(ROOT -> RIGHT,ITEM) [END OF IF] [END OF IF] •Step 2: END
  • 57. Example  Consider key = 45 has to be searched in the given BST- 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 57 •We start our search from the root node 25. •As 45 > 25, so we search in 25’s right subtree. •As 45 < 50, so we search in 50’s left subtree. •As 45 > 35, so we search in 35’s right subtree. •As 45 > 44, so we search in 44’s right subtree but 44 has no subtrees. •So, we conclude that 45 is not present in the above BST.
  • 58. 2. Insertion Operation  Rules-  Insert function is used to add a new element in a binary search tree at appropriate location. Insert function is to be designed in such a way that, it must node violate the property of binary search tree at each value.  Allocate the memory for tree.  Set the data part to the value and set the left and right pointer of tree, point to NULL.  If the item to be inserted, will be the first element of the tree, then the left and right of this node will point to NULL.  Else, check if the item is less than the root element of the tree, if this is true, then recursively perform this operation with the left of the root.  If this is false, then perform this operation recursively with the right sub-tree of the root. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 58
  • 59. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 59 Insert (ROOT, ITEM) •Step 1: IF ROOT = NULL Allocate memory for TREE SET ROOT -> DATA = ITEM SET ROOT -> LEFT = ROOT -> RIGHT = NULL ELSE IF ITEM < ROOT -> DATA Insert(ROOT -> LEFT, ITEM) ELSE Insert(ROOT -> RIGHT, ITEM) [END OF IF] [END OF IF] •Step 2: END
  • 60. struct node* insert(struct node* node, int data) { /* If the tree is empty, return a new node */ if (node == NULL) return newNode(data); /* Recur down the tree */ if (data < node->data) node->left = insert(node->left, data); else if (data > node->data) node->right = insert(node->right, data); return node; } 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 60 struct node *newNode(int item) { struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->data = item; temp->left = temp->right = NULL; return temp; }
  • 61. Example  Consider the following example where key = 40 is inserted in the given BST- We start searching for value 40 from the root node 100.  As 40 < 100, so we search in 100’s left subtree.  As 40 > 20, so we search in 20’s right subtree.  As 40 > 30, so we add 40 to 30’s right subtree. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 61
  • 62. FIND MIN  Approch for finding minimum element:  Traverse the node from root to left recursively until left is NULL.  The node whose left is NULL is the node with minimum value. int minValue(struct node* root) { struct node* current = root; /* loop down to find the leftmost leaf */ while (current->left != NULL) { current = current->left; } return(current->key); } 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 62
  • 63. FIND MIN 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 63
  • 64. FIND MAX  Approch for finding maximum element:  Traverse the node from root to right recursively until right is NULL.  The node whose right is NULL is the node with maximum value.  int maxValue(struct node* root)  {  struct node* current = root;  /* loop down to find the leftmost leaf */  while (current->right != NULL)  {  current = current->right;  }  return(current->key);  } 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 64
  • 65. FIND MAX 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 65
  • 66. Time Complexity:  O(N) Worst case happens for left skewed trees in finding the minimum value. O(N) Worst case happens for right skewed trees in finding the maximum value.  O(1) Best case happens for left skewed trees in finding the maximum value. O(1) Best case happens for right skewed trees in finding the minimum value. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 66
  • 67. 3. Deletion Operation  Deletion Operation is performed to delete a particular element from the Binary Search Tree. • Case-01: Deletion Of A Node Having No Child (Leaf Node) • Case-02: Deletion Of A Node Having Only One Child • Case-02: Deletion Of A Node Having Two Children 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 67
  • 68. Case-01: Deletion Of A Node Having No Child (Leaf Node)  It is the simplest case, in this case, replace the leaf node with the NULL and simple free the allocated space.  In the following image, we are deleting the node -4, since the node is a leaf node, therefore the node will be replaced with NULL and allocated space will be freed.  Example-Remove -4 from a BST. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 68
  • 69. Case-02: Deletion Of A Node Having Only One Child  In this case, replace the node with its child and delete the child node, which now contains the value which is to be deleted. Simply replace it with the NULL and free the allocated space.  Example : 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 69
  • 70. Case-02: Deletion Of A Node Having Two Children  A node with two children may be deleted from the BST in the following two ways-  Method-01:  Visit to the right subtree of the deleting node.  Pluck the least value element called as inorder successor.  Replace the deleting element with its inorder successor. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 70
  • 71.  struct node* delete_node(struct node* root, int data)  {  if (root == NULL)  return root;  // If the key to be deleted is smaller than the root's key,  if (data < root->data)  root->left = delete_node(root->left, data);  // If the key to be deleted is greater than the root's key,  else if (data > root->data)  root->right = delete_node(root->right, data);  else  { 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 71 // node with only one child or no child 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; } // node with two children: struct node* temp = minValueNode(root->right); // Copy the inorder successor's content to this node root->data = temp->data; // Delete the inorder successor root->right = delete_node(root->right, temp->data); } return root; }
  • 72.  Algorithm  Delete (ROOT, ITEM)  Step 1: IF ROOT = NULL Write "item not found in the tree" // If the key to be deleted is smaller than the root's key, then it lies in left subtree ELSE IF ITEM < TREE -> DATA Delete(ROOT->LEFT, ITEM) // If the key to be deleted is greater than the root's key, // then it lies in right subtree ELSE IF ITEM > ROOT -> DATA Delete(ROOT-> RIGHT, ITEM) // node with two children: Get the inorder predecessor(largest in the left subtree) ELSE IF ROOT -> LEFT AND ROOT -> RIGHT SET TEMP = findmax(TREE -> LEFT) SET ROOT -> DATA = TEMP -> DATA Delete(ROOT -> LEFT, TEMP -> DATA) 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 72 // node with only one child or no child ELSE SET TEMP = ROOT IF ROOT -> LEFT = NULL AND ROOT-> RIGHT = NULL SET ROOT = NULL ELSE IF ROOT -> LEFT != NULL SET ROOT = ROOT -> LEFT ELSE SET ROOT = ROOT -> RIGHT [END OF IF] FREE TEMP [END OF IF] Step 2: END
  • 75. Example  Consider the following example where node with value = 15 is deleted from the BST- 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 75
  • 76. Method-02:  Visit to the left subtree of the deleting node.  Pluck the greatest value element called as inorder predecessor.  Replace the deleting element with its inorder predecessor.  Consider the following example where node with value = 15 is deleted from the BST- 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 76
  • 77. Advantages of using binary search tree  Searching become very efficient in a binary search tree since, we get a hint at each step, about which sub-tree contains the desired element.  The binary search tree is considered as efficient data structure in compare to arrays and linked lists. In searching process, it removes half sub-tree at every step. Searching for an element in a binary search tree takes o(log2n) time. In worst case, the time it takes to search an element is 0(n).  It also speed up the insertion and deletion operations as compare to that in array and linked list. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 77
  • 78. TIME COMPLEXITY  Time complexity of all BST Operations = O(h).  Here, h = Height of binary search tree  Worst Case-  In worst case,  The binary search tree is a skewed binary search tree.  Height of the binary search tree becomes n.  So, Time complexity of BST Operations = O(n).  In this case, binary search tree is as good as unordered list with no benefits. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 78
  • 79.  Best Case-  In best case,  The binary search tree is a balanced binary search tree.  Height of the binary search tree becomes log(n).  So, Time complexity of BST Operations = O(logn). 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 79
  • 80. APPLICATIONS -BST 1) Used to express arithmetic expressions 2) Used to evaluate expression trees. 3) Used for indexing IP addresses. 4) It is used to implement dictionary. 5) It is used to implement multilevel indexing in DATABASE. 7) To implement Huffman Coding Algorithm. 8) It is used to implement searching Algorithm. 9) Implementing routing table in router. 3/5/2022 VELAMMAL ENGINEERING COLLEGE, Dept. of CSE 80
  • 81. What is a Tree?  In CS a tree is  an Organizational Structure for the storage and retrieval of data.  Height balanced binary search trees: AVL trees, red-black trees search faster than in an average binary search tree because the tree is guaranteed to have the smallest possible depth.  Another kind of multi-way search trees . Optimises search in external memory.
  • 82. Two types of memory  Main memory (RAM)  External (peripheral) storage: hard disk, CD-ROM, tape, etc. Different considerations are important in designing algorithms and data structures for primary (main) versus secondary (peripheral) memory.
  • 83. BST Binary Search Tree Time Complexity : O(log(n)) Unbalanced Binary Search Tree Time Complexity : O(n) for search, insert and delete operations
  • 84. What is the remedy??  Remedy is self balancing trees.  Automatically adjust to itself to get balanced.  eg Red black tree  B-Tree
  • 85. What is B tree ?  Intro  Invented by Rudolf Bayer and Ed McCreight in 1972 at Boeing Research Labs.  B-Tree is known as balanced m-way tree and used in external sorting.  m-way node is were m=5 it describes that there should be m links and m-1 data.  Algorithms and data structures for external memory as opposed to the main memory
  • 86. B Tree  A good example of a data structure for external memory is a B-tree.  Better than binary search trees if data is stored in external memory (they are NOT better with in-memory data!).  Each node in a tree should correspond to a block of data.  Each node stores many data items and has many successors (stores addresses of successor blocks).
  • 87.  The tree has fewer levels but search for an item involves more comparisons at each level.  There is a single root node, which may have only one record and two children (or none if the tree is empty).
  • 88. Properties of B tree  Each node has a maximum of M children and minimum of m/2 children  Each node should have a fewer keys than children with a maximum of m-1 keys  Keys should be arranged in a defined order within the node  Key to be inserted into a fullnode, the node is splitted
  • 89. B tree Example With Order m=4 & m=5 m=4 Maximum Children - 4 Minimum Children - Ceil (m/2) = 2 Maximum Keys - (m-1) =3 Min Keys - Ceil(m/2)-1 =1 m=5 Maximum Children - 5 Minimum Children - Ceil (m/2) = 3 Maximum Keys - (m-1) =4 Min Keys - Ceil(m/2)-1 =2
  • 90. Operations on B trees  Basic three opeartions  Insertion  Insertion will be done in the leaf nodes  Deletion  Search
  • 91. Search for record with key 40:
  • 93.
  • 95. Inserting 53: the node is too full!
  • 96. Find the Middle Element
  • 98.
  • 99. Insertion with even order  To insert elements in B tree element to be inserted is to be scanned from left to right.  If the order to construct an even order B tree then two sets of tree is created
  • 100. Inserting in a B-Tree  Find the node where the item is to be inserted by following the search procedure.  If the node is not full, insert the item into the node in order.  If the node is full, it has to be split.
  • 101. Example  Construct a B-Tree of order 4 with following set of datas 5,3,21,9,1,13,2,7,10,12,4,8 m=4 max keys=m-1 =3
  • 103.
  • 104.
  • 105. Deletion in B tree  The key to be deleted is called the target key Two Possibilities  Target key can be a leaf node  Target Key can be in internal node
  • 106. Contd..  Target key can be leaf node Two Possibilities  Leaf node contains more than min no of keys  Leaf node contains min no of keys 
  • 107. Contd..  If the target key is internal node 