SlideShare a Scribd company logo
Department of
Computer Science and Engineering
DATA STRUCTURES
School of Computing
Vel Tech Rangarajan Dr. Sagunthala R&D Institute of
Science and Technology
Year : 2019-23
Course Code : 1151CS102
Course Category : Program Core
Unit No : II
Topic : Trees
Faculty Name : Mrs.A.SANGEETHA
Department of Computer Science and Engineering
COURSE DETAILS
02-02-2023 2
and Project
Management
(SEPM)
Preamble:
This course provides an introduction to the basic concepts and techniques of
Linear and nonlinear data Structures and Analyze the various algorithm.
1150CS201 Problem Solving using C
•Prerequisite Courses:
Sl. No Course Code Course Name
1 1151CS105 System Software
2 1151CS106 Design and Analysis of Algorithm
3 1151CS107 Database Management System
4 1151CS108 Operating Systems
5 1151CS111 Computer Networks
•Related Courses:
Department of Computer Science and Engineering
COURSE OUTCOMES
02-02-2023 3
 Identify and explain user defined data types, linear data structures for
solving real world problems.
 Design modular programs on non linear data structures and
algorithms for solving engineering problems efficiently.
 Illustrate special trees and Hashing Techniques.
 Apply searching techniques in graph traversal
 Apply sorting techniques for real world problems.
Department of Computer Science and Engineering
AGENDA
02-02-2023 4
and Project
Management
(SEPM)
 Introduction to trees
 Tree
 Binary Trees
 Definitions
 Expression Tree
 Binary Tree Traversals
 The Search Tree ADT
 Binary Search Trees
 AVL Tree.
Department of Computer Science and Engineering 5
NON LINEAR DATA STRUCTURES
•Data elements are not arranged sequentially or linearly
•Supports multi-level storage
Tree
Graph
02-02-2023
Department of Computer Science and Engineering 6
COMPARISON
02-02-2023
Department of Computer Science and Engineering 7
TREE
• Tree is a hierarchical data structure which stores the
information naturally in the form of hierarchy style
• Collection of nodes (starting at a root node) together with a list
of references to nodes (the "children")
02-02-2023
Department of Computer Science and Engineering 8
WHY?
organize all of their recordsintoa computerdatabase.
 The first thing you are asked to do is create a database of names
withall thecompany'smanagement and employees.
 T
ostart yourwork,youmakea listof everyoneinthe companyalong
withtheir positionandother details.
 Imagine that you are hired by company XYZ to
02-02-2023
Department of Computer Science and Engineering 9
WHY?
EmployeesTable
02-02-2023
Department of Computer Science and Engineering 10
WHY?
EmployeesTable
02-02-2023
Department of Computer Science and Engineering 11
TERMINOLOGIES
02-02-2023
Department of Computer Science and Engineering 12
TERMINOLOGIES
1. Root-
•The first node from where the tree originates is called as a root node.
•Doesn’t have parent node
02-02-2023
Department of Computer Science and Engineering 13
TERMINOLOGIES
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.
02-02-2023
Department of Computer Science and Engineering 14
TERMINOLOGIES
3. Parent-
•The node which has a branch from it to any other node is called as a parent node.
•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.
02-02-2023
Department of Computer Science and Engineering 15
TERMINOLOGIES
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.
02-02-2023
Department of Computer Science and Engineering 16
TERMINOLOGIES
5. Siblings-
•Nodes which belong to the same parent are called as siblings.
•In other words, nodes with the same parent are sibling nodes.
02-02-2023
Department of Computer Science and Engineering 17
TERMINOLOGIES
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.
02-02-2023
Department of Computer Science and Engineering 18
TERMINOLOGIES
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.
02-02-2023
Department of Computer Science and Engineering 19
TERMINOLOGIES
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.
02-02-2023
Department of Computer Science and Engineering 20
TERMINOLOGIES
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.
02-02-2023
Department of Computer Science and Engineering 21
TERMINOLOGIES
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
02-02-2023
Department of Computer Science and Engineering 22
TERMINOLOGIES
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
02-02-2023
Department of Computer Science and Engineering 23
TERMINOLOGIES
12. Subtree-
•In a tree, each child from a node forms a subtree recursively.
•Every child node forms a subtree on its parent node.
02-02-2023
Department of Computer Science and Engineering 24
TERMINOLOGIES
12. Subtree-
•In a tree, each child from a node forms a subtree recursively.
•Every child node forms a subtree on its parent node.
02-02-2023
Department of Computer Science and Engineering 25
EXAMPLE
02-02-2023
Department of Computer Science and Engineering 26
REPRESENTATION
•List Representation
•Left Child - Right Sibling Representation
02-02-2023
Department of Computer Science and Engineering 27
REPRESENTATION - EXAMPLE
02-02-2023
Department of Computer Science and Engineering 28
LIST REPRESENTATION
02-02-2023
Department of Computer Science and Engineering 29
LEFT CHILD RIGHT SIBLING
02-02-2023
Department of Computer Science and Engineering 30
BINARY TREE
A binary tree is a tree where all nodes have zero, oneor two children
 A binary tree is either:
— an empty tree
— consists of a node, called a root, and zero, one, ortwo children
(left and right), each of which are themselves binary trees
 Every non-empty node has two children, either of which may
be empty
02-02-2023
Department of Computer Science and Engineering 31
BINARY TREE
02-02-2023
Department of Computer Science and Engineering 32
BINARY TREE
02-02-2023
Department of Computer Science and Engineering 33
TREE VS BINARY TREE
02-02-2023
Department of Computer Science and Engineering 34
REPRESENTATION
Array Representation
Linked List Representation
02-02-2023
Department of Computer Science and Engineering 35
ARRAY REPRESENTATION
• Array representation
– The root of the tree is stored in position 0.
– The node in position i, is the implicit father of nodes 2i+1 and
2i+2.
– Left child is at 2i+1 and right at 2i+2.
02-02-2023
Department of Computer Science and Engineering 36
ARRAY REPRESENTATION
X
Y Z
A
B C
0 1 2 3 4 5 6 7 8 10 12
X Y Z A B C
9 11
02-02-2023
Department of Computer Science and Engineering 37
LINKED LIST REPRESENTATION
• Every node will consists of information, and two pointers left and
right pointing to the left and right child nodes.
struct node
{
int data;
struct node *left;
struct node *right;
};
B
A D
C
02-02-2023
Department of Computer Science and Engineering 38
TYPES
Full binary tree: Every node other than leaf nodes has 2
child nodes.
Complete binary tree: All levels are filled except possibly
the last one, and all nodes are filled in as far left as possible.
Perfect binary tree: All nodes have two children and all
leaves are at the same level.
02-02-2023
Department of Computer Science and Engineering 39
TYPES
FULL BINARY
TREE
PERFECT
BINARY TREE
COMPLETE BINARY
TREE
02-02-2023
Department of Computer Science and Engineering 40
•Binary tree in which the leaf nodes are operands and the interior
nodes are operators.
EXPRESSION TREE
02-02-2023
Department of Computer Science and Engineering 41
Constructing an Expression Tree
Steps :
1. Read one symbol at a time from the postfix expression.
2. Check whether the symbol is an operand or operator.
(a) If the symbol is an operand, create a one - node tree and push a
pointer on to the stack.
(b) If the symbol is an operator pop two pointers from the stack
namely T1 and T2 and form a new tree with root as the operator
and T2 as a left child and T1 as a right child.
A pointer to this new tree is then pushed onto the stack.
EXPRESSION TREE
02-02-2023
Department of Computer Science and Engineering 42
EXPRESSION TREE
A*(B-C) + (D+E)
02-02-2023
Department of Computer Science and Engineering 43
EXPRESSION TREE-PROBLEM
A+B*(C/D)^E%F
02-02-2023
Department of Computer Science and Engineering
BINARY SEARCH TREE
02-02-2023 44
and Project
Management
(SEPM)
• Binary tree in which for every node X in the tree,
• keys in its left subtree < the key value in X
• keys in its right subtree > key value in X.
Department of Computer Science and Engineering
BINARY SEARCH TREE
02-02-2023 45
and Project
Management
(SEPM)
• Binary tree in which for every node X in the tree,
• keys in its left subtree < the key value in X
• keys in its right subtree > key value in X.
Department of Computer Science and Engineering
DEFINITION
02-02-2023 46
and Project
Management
(SEPM)
A Binary Search Tree (BST) is a tree in which all the
nodes follow the below-mentioned properties −
 The value of the key of the left sub-tree is less than
the value of its parent (root) node's key.
 The value of the key of the right sub-tree is greater
than or equal to the value of its parent (root) node's key.
USE:
used to construct more abstract data structures such
as sets, multisets, and associative arrays.
Department of Computer Science and Engineering
BINARY SEARCH TREE - CONSTRUCTION
02-02-2023 47
and Project
Management
(SEPM)
Construct a Binary Search Tree (BST) for the following
sequence of numbers-
50, 70, 60, 20, 90
• When elements are given in a sequence,
• Always consider the first element as the root node.
Consider the given elements and insert them in the BST one
by one.
Department of Computer Science and Engineering
BINARY SEARCH TREE - CONSTRUCTION
02-02-2023 48
and Project
Management
(SEPM)
Insert 50
Department of Computer Science and Engineering
BINARY SEARCH TREE - CONSTRUCTION
02-02-2023 49
and Project
Management
(SEPM)
Insert 70
As 70 > 50, so insert 70 to the right of 50.
Department of Computer Science and Engineering
BINARY SEARCH TREE - CONSTRUCTION
02-02-2023 50
and Project
Management
(SEPM)
Insert 60
As 60 > 50, so insert 60 to the right of 50.
As 60 < 70, so insert 60 to the left of 70
Department of Computer Science and Engineering
BINARY SEARCH TREE - CONSTRUCTION
02-02-2023 51
and Project
Management
(SEPM)
Insert 20
As 20 < 50, so insert 20 to the left of 50.
Department of Computer Science and Engineering
BINARY SEARCH TREE - CONSTRUCTION
02-02-2023 52
and Project
Management
(SEPM)
Insert 90
As 90 > 50, so insert 90 to the right of 50.
As 90 > 70, so insert 90 to the right of 70.
Department of Computer Science and Engineering
DECLARATION
02-02-2023 53
and Project
Management
(SEPM)
Struct TreeNode;
typedef struct TreeNode * SearchTree;
SearchTree Insert (int X, SearchTree T);
SearchTree Delete (int X, SearchTree T);
int Find (int X, SearchTree T);
int FindMin (Search Tree T);
int FindMax (SearchTree T);
SearchTree MakeEmpty (SearchTree T);
Struct TreeNode
{
int Element ;
SearchTree Left;
SearchTree Right;
};
Department of Computer Science and Engineering
MAKE EMPTY
02-02-2023 54
and Project
Management
(SEPM)
SearchTree MakeEmpty (SearchTree T)
{
if (T! = NULL)
{
MakeEmpty (T left);
MakeEmpty (T Right);
free (T);
}
return NULL ;
}
Department of Computer Science and Engineering
INSERTION - ALGORITHM
02-02-2023 55
and Project
Management
(SEPM)
Step 1 - Create a newNode with given value and set
its left and right to NULL.
Step 2 - Check whether tree is Empty.
Step 3 - If the tree is Empty, then set root to newNode.
Step 4 - If the tree is Not Empty, then check whether the value of
newNode is smaller or larger than the node (here it is root node).
Step 5 - If newNode is smaller than or equal to the node then
move to its left child. If newNode is larger than the node then
move to its right child.
Department of Computer Science and Engineering
INSERTION - ALGORITHM
02-02-2023 56
and Project
Management
(SEPM)
Step 6- Repeat the above steps until we reach to the leaf node
(i.e., reaches to NULL).
Step 7 - After reaching the leaf node, insert the newNode as left
child if the newNode is smaller or equal to that leaf node or else
insert it as right child.
Department of Computer Science and Engineering
INSERTION
02-02-2023 57
and Project
Management
(SEPM)
SearchTree Insert (int X, searchTree T)
if (T = = NULL)
T = malloc (size of (Struct TreeNode));
if (T! = NULL)
T →Element = X;
T→ left = NULL;
T →Right = NULL;
else if (X < T →Element)
T → left = Insert (X, T →left)
else if (X > T →Element)
T → Right = Insert (X, T →Right)
return T
Department of Computer Science and Engineering
INSERTION - EXAMPLE
02-02-2023 58
and Project
Management
(SEPM)
Department of Computer Science and Engineering
INSERTION - EXAMPLE
02-02-2023 59
and Project
Management
(SEPM)
Department of Computer Science and Engineering
FIND - ALGORITHM
02-02-2023 60
and Project
Management
(SEPM)
Step 1 - Read the search element from the user.
Step 2 - Compare the search element with the 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 node value.
Step 5 - If search element is smaller, then continue the search
process in left subtree.
Department of Computer Science and Engineering
FIND - ALGORITHM
02-02-2023 61
and Project
Management
(SEPM)
Step 6- If search element is larger, then continue the search
process in right subtree.
Step 7 - Repeat the same until we find the exact element or until
the search element is compared with the leaf node
Step 8 - If we reach to the node having the value equal to the
search value then display "Element is found" and terminate the
function.
Step 9 - If we reach to the leaf node and if it is also not matched
with the search element, then display "Element is not found"
and terminate the function.
Department of Computer Science and Engineering
FIND
02-02-2023 62
and Project
Management
(SEPM)
Find (int X, SearchTree T)
if T = = NULL
return NULL
if (X < T → Element)
return Find (X, T →left);
else If (X > T→ Element)
return Find (X, T →Right)
else
return T
Department of Computer Science and Engineering
FIND MIN
02-02-2023 63
and Project
Management
(SEPM)
•returns the position of the smallest element in the tree.
RECURISVE ROUTINE FOR FINDMIN
FindMin (SearchTree T)
if (T = = NULL)
return NULL
else if (T →left = = NULL)
return T
else
return FindMin (T → left)
Department of Computer Science and Engineering
FIND MIN – NON RECURSIVE
02-02-2023 64
and Project
Management
(SEPM)
FindMin (SearchTree T)
if (T! = NULL)
while (T →Left ! = NULL)
T = T →Left ;
return T
Department of Computer Science and Engineering
FIND MAX
02-02-2023 65
and Project
Management
(SEPM)
•return the position of largest elements in the tree.
RECURISVE ROUTINE FOR FINDMAX
FindMax (SearchTree T)
if T is NULL
return NULL
else if T →Right = = NULL
return T
else FindMax (T →Right);
}
Department of Computer Science and Engineering
FIND MAX– NON RECURSIVE
02-02-2023 66
and Project
Management
(SEPM)
int FindMax (SearchTree T)
if (T! = NULL)
while (T Right ! = NULL)
T = T →Right ;
return T ;
Department of Computer Science and Engineering
DELETION
02-02-2023 67
and Project
Management
(SEPM)
To delete an element, consider the following three
possibilities.
• CASE 1 Node to be deleted is a leaf node (ie) No
children.
• CASE 2 Node with one child.
• CASE 3 Node with two children.
Department of Computer Science and Engineering
CASE 1 ALGORITHM
02-02-2023 68
and Project
Management
(SEPM)
Deleting a leaf node
Step 1 Find the node to be deleted using search operation
Step 2 Delete the node using free function (If it is a leaf) and
terminate the function.
Department of Computer Science and Engineering
CASE 1 EXAMPLE
02-02-2023 69
and Project
Management
(SEPM)
Department of Computer Science and Engineering
CASE 2 ALGORITHM
02-02-2023 70
and Project
Management
(SEPM)
Deleting a node with one child
Step 1 - Find the node to be deleted using search operation
Step 2 - If it has only one child then create a link between its
parent node and child node.
Step 3 - Delete the node using free function and terminate the
function.
Department of Computer Science and Engineering
CASE 2 EXAMPLE
02-02-2023 71
and Project
Management
(SEPM)
Department of Computer Science and Engineering
CASE 3 ALGORITHM
02-02-2023 72
and Project
Management
(SEPM)
Deleting a node with two children
Step 1 - Find the node to be deleted using search operation
Step 2 - If it has two children, then find the largest node in its left
subtree (OR) the smallest node in its right subtree.
Step 3 - Swap both deleting node and node which is found in the above
step.
Step 4 - Then check whether deleting node came to case 1 or case 2 or
else goto step 2
Step 5 - If it comes to case 1, then delete using case 1 logic.
Step 6- If it comes to case 2, then delete using case 2 logic.
Step 7 - Repeat the same process until the node is deleted from the tree.
Department of Computer Science and Engineering
CASE 3 EXAMPLE
02-02-2023 73
and Project
Management
(SEPM)
Taking the smallest node in its right subtree
Department of Computer Science and Engineering
CASE 3 EXAMPLE
02-02-2023 74
and Project
Management
(SEPM)
Taking the largest node in its left subtree
Department of Computer Science and Engineering
DELETION
02-02-2023 75
and Project
Management
(SEPM)
SearchTree Delete (X, T)
Declare Tmpcell ;
if (T = = NULL)
Error ("Element not found")
else if (X < T →Element)
T →Left = Delete (X, T Left)
else if (X > T Element)
T →Right = Delete (X, T →Right)
Department of Computer Science and Engineering
DELETION
02-02-2023 76
and Project
Management
(SEPM)
else // Two children
if (T→ Left && T→ Right)
// Replace with smallest data in right subtree
Tmpcell = FindMin (T→ Right)
T →Element = Tmpcell → Element
T →Right = Delete (T → Element; T →Right)
Department of Computer Science and Engineering
DELETION
02-02-2023 77
and Project
Management
(SEPM)
else // one or zero children
Tmpcell = T
if (T →Left = = NULL)
T = T→ Right
else if (T→ Right = = NULL)
T = T →Left
free (TmpCell)
return T
Department of Computer Science and Engineering
EXAMPLE
02-02-2023 78
and Project
Management
(SEPM)
Department of Computer Science and Engineering
TREE TRAVERSAL
02-02-2023 79
and Project
Management
(SEPM)
The process of visiting (checking and/or updating)
each node in a tree data structure
Department of Computer Science and Engineering 80
TYPES
In order traversal
Pre order traversal
Post order traversal
02-02-2023
Department of Computer Science and Engineering 81
IN ORDER TRAVERSAL
• Process all nodes of a tree by recursively
processing the left subtree, then processing the root,
and finally the right subtree
02-02-2023
Department of Computer Science and Engineering 82
ALGORITHM
Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)
02-02-2023
Department of Computer Science and Engineering 83
PSEUDOCODE - RECURSIVE
inorder(node)
if (node == null)
return
inorder(node.left)
visit(node)
inorder(node.right)
02-02-2023
Department of Computer Science and Engineering 84
PSEUDOCODE - ITERATIVE
iterativeInorder(node)
s ← empty stack
while (not s.isEmpty() or node ≠ null)
if (node ≠ null)
s.push(node)
node ← node.left
else
node ← s.pop()
visit(node)
node ← node.right
02-02-2023
Department of Computer Science and Engineering 85
EXAMPLE
02-02-2023
Department of Computer Science and Engineering 86
EXAMPLE
02-02-2023
Department of Computer Science and Engineering 87
PRE ORDER TRAVERSAL
Preorder traversal of a binary tree is defined as follow
 Process the root node
 Traverse the left subtree in preorder
 Traverse the right subtree in preorder
If particular subtree is empty (i.e., node has no left or right
descendant) the traversal is performed by doing nothing, In other
words, a null subtree is considered to be fully traversed when it is
encountered.
02-02-2023
Department of Computer Science and Engineering 88
ALGORITHM
Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)
02-02-2023
Department of Computer Science and Engineering 89
PSEUDOCODE - RECURSIVE
preorder(node)
if (node == null)
return
visit(node)
preorder(node.left)
preorder(node.right)
02-02-2023
Department of Computer Science and Engineering 90
PSEUDOCODE - ITERATIVE
iterativePreorder(node)
if (node == null)
return
s ← empty stack
s.push(node)
while (not s.isEmpty())
node ← s.pop()
visit(node)
if node.right ≠ null
s.push(node.right)
if node.left ≠ null
s.push(node.left)
02-02-2023
Department of Computer Science and Engineering 91
EXAMPLE
02-02-2023
Department of Computer Science and Engineering 92
EXAMPLE
02-02-2023
Department of Computer Science and Engineering 93
POST ORDER
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.
02-02-2023
Department of Computer Science and Engineering 94
ALGORITHM
Algorithm Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root.
02-02-2023
Department of Computer Science and Engineering 95
PSEUDOCODE - RECURSIVE
postorder(node)
if (node == null)
return
postorder(node.left)
postorder(node.right)
visit(node)
02-02-2023
Department of Computer Science and Engineering 96
PSEUDOCODE - ITERATIVE
iterativePostorder(node)
s ← empty stack
lastNodeVisited ← null
while (not s.isEmpty() or node ≠ null)
if (node ≠ null)
s.push(node)
node ← node.left
else
peekNode ← s.peek
if (peekNode.right ≠ null and lastNodeVisited ≠
peekNode.right)
node ← peekNode.right
else visit(peekNode)
lastNodeVisited ← s.pop()
02-02-2023
Department of Computer Science and Engineering 97
EXAMPLE
02-02-2023
Department of Computer Science and Engineering 98
EXAMPLE
02-02-2023
Department of Computer Science and Engineering 99
ILLUSTRATION
• Assume: visiting a node is
printing its label
• Preorder:
1 3 5 4 6 7 8 9 10 11 12
• Inorder:
4 5 6 3 1 8 7 9 11 10 12
• Postorder:
4 6 5 3 8 11 12 10 9 7 1
1
3
11
9
8
4 6
5
7
1
2
1
0
02-02-2023
Department of Computer Science and Engineering 100
PROBLEM
02-02-2023
Department of Computer Science and Engineering 101
APPLICATION
•In-order traversal is very commonly used on binary search
trees because it returns values from the underlying set in order,
according to the comparator that set up the binary search tree.
•Post-order traversal while deleting or freeing nodes and values
can delete or free an entire binary tree.
•Expression Tree
02-02-2023
Department of Computer Science and Engineering
AVL TREE - AGENDA
02-02-2023 102
and Project
Management
(SEPM)
•Drawbacks of BST
•Balanced Binary Trees
•What is AVL Tree?
•Characteristics
•Operations
•Implementation
•Advantages &Disadvantages
•Applications
Department of Computer Science and Engineering
DRAWBACKS OF BST
02-02-2023 103
and Project
Management
(SEPM)
● The disadvantage of a binary search tree is that its height
can be as large as N-1
● Worst case running time is O(N)
■ What happens when you Insert elements in
ascending order?
○ Insert: 2, 4, 6, 8, 10, 12 into an empty BST
■ Problem: Lack of “balance”:
○ compare depths of left and right subtree
■ Unbalanced degenerate tree
Department of Computer Science and Engineering 104
BALANCED VS UNBALANCED BST
02-02-2023
Department of Computer Science and Engineering 105
APPROACHES TO BALANCING TREES
● Don't balance
■ May end up with some nodes very deep
● Strict balance
■ The tree must always be balanced perfectly
● Pretty good balance
■ Only allow a little out of balance
● Adjust on access
■ Self-adjusting
02-02-2023
Department of Computer Science and Engineering 106
AVL TREE
Adelson-Velskii and Landis
 for each node, the height of the left and right subtrees
can differ at most 1,-1,0.
Binary search tree with balance condition in which the sub-
trees of each node can differ by at most 1 in their height
02-02-2023
Department of Computer Science and Engineering 107
AVL TREE
AVL property
violated here
AVL tree
02-02-2023
Department of Computer Science and Engineering 108
CHARACTERISTICS
• Each node can hold a maximum of two child nodes.
• Each node can carry only one key value.
• The height of the child nodes of any time must differ in height
by no more than 1.
• When there is a difference in height of more than 1 or less than
-1 between the child nodes of a particular node, the tree goes
through the process of rebalancing through a series of rotations
until it is re-balanced.
02-02-2023
Department of Computer Science and Engineering 109
MINNIMUM NO OF NODES
N1 = 2 N2 =4 N3 = N2+N1+1=7
N0 = 1
■ N(h) = minimum number of nodes in anAVL tree of height h
■ N(h) = N(h-1) + N(h-2) + 1
02-02-2023
Department of Computer Science and Engineering 110
OPERATIONS
•INSERTION
•DELETION
•SEARCH
02-02-2023
Department of Computer Science and Engineering 111
BALANCE FACTOR
BF= height of left subtree– height of right subtree
02-02-2023
Department of Computer Science and Engineering 112
NODE DECLARATION
struct Node
{
int key;
struct Node *left;
struct Node *right;
int height;
};
02-02-2023
Department of Computer Science and Engineering 113
INSERTION
• Insert will be done recursively
• the insert call will return true if the height of the sub-tree has
changed
• if insert() returns true, balance factor of current node needs
to be adjusted
○ balance factor = height(left) – height(right)
• if balance factor equals 2 for any node, the sub- tree must be
rebalanced
02-02-2023
Department of Computer Science and Engineering 114
ALGORITHM
Step 1: First, insert a new element into the tree using BST's (Binary
Search Tree) insertion logic.
Step 2: After inserting the elements you have to check the Balance
Factor of each node.
Step 3: When the Balance Factor of every node will be found like 0 or 1
or -1 then the algorithm will proceed for the next operation.
Step 4: When the balance factor of any node comes other than the above
three values then the tree is said to be imbalanced. Then perform the
suitable Rotation to make it balanced and then the algorithm will
proceed for the next operation.
02-02-2023
Department of Computer Science and Engineering 115
REBALANCING
● To check if a tree needs to be rebalanced
■ start at the parent of the inserted node and journey up the
tree to the root
○ if a node’s balance factor becomes 2 need to do a
rotation in the sub-tree rooted at the node
○ once sub-tree has been re-balanced, guaranteed that the
rest of the tree is balanced as well
 can just return false from the insert() method
■ 4 possible cases for re-balancing
02-02-2023
Department of Computer Science and Engineering 116
POSSIBLE CASES
There are 4 cases:
Outside Cases (require single rotation) :
1. Insertion into left subtree of left child of node A
2. Insertion into right subtree of right child of node A
Inside Cases (require double rotation) :
3. Insertion into right subtree of left child of node A
4. Insertion into left subtree of right child of node A
02-02-2023
Department of Computer Science and Engineering 117
CASE1-RIGHT ROTATION
02-02-2023
Department of Computer Science and Engineering 118
CASE 2 – LEFT ROTATION
02-02-2023
Department of Computer Science and Engineering 119
LEFT & RIGHT ROTATIONS
02-02-2023
Department of Computer Science and Engineering 120
CASE 3 – RIGHT SUBTREE LEFT CHILD
02-02-2023
Department of Computer Science and Engineering 121
CASE 4 – LEFTSUBTREE RIGHT CHILD
02-02-2023
Department of Computer Science and Engineering 122
INSERTION - EXAMPLE
02-02-2023
Department of Computer Science and Engineering 123
INSERTION
INSERT(T, n)
temp = T->root
y = NULL
while temp != NULL
y = temp
if n->data < temp->data
temp = temp->left
else
temp = temp->right
n->parent = y
if y==NULL
T->root = n
02-02-2023
Department of Computer Science and Engineering 124
else if n->data < y->data
y->left = n
else
y->right = n
z = n
while y != NULL
y->height = 1 + MAX(HEIGHT(y->left), HEIGHT(y->right))
x = y->parent
if BALANCE-FACTOR(x) <= -2 or BALANCE-FACTOR(x) >= 2
if y == x->left
if z == x->left->left //case1
RIGHT_ROTATE(T, x)
INSERTION
02-02-2023
Department of Computer Science and Engineering 125
else if z == x.left.right //case 3
LEFT_ROTATE(T, y)
RIGHT_ROTATE(T, x)
else if y == x->right
if z == x->right->right //case 2
LEFT_ROTATET(T, x)
else if z == x->right->left //case 4
RIGHT_ROTATE(T, y)
LEFT_ROTATE(T, x)
break
y = y->parent
z = z->parent
INSERTION
02-02-2023
Department of Computer Science and Engineering 126
SEARCH
● Searching an AVL tree is exactly the same as
searching a regular binary tree
■ all descendants to the right of a node are greater than
the node
■ all descendants to the left of a node are less than the
node
02-02-2023
Department of Computer Science and Engineering 127
SEARCH
SEARCH(x, T)
if(T->root != null)
if(T->root->data == x)
return r
else if(T->root->data > x)
return SEARCH(x, T->root->left)
else
return SEARCH(x, T->root->right)
02-02-2023
Department of Computer Science and Engineering 128
DELETION -ALGORITHM
Step 1: First, find that node where k is stored
Step 2: Delete those contents of the node (Suppose the node is x)
Step 3: Claim: Deleting a node in an AVL tree can be reduced by deleting a leaf.
There are three possible cases:
•When x has no children then, delete x
•When x has one child, let x' becomes the child of x.
then replace the contents of x with the contents of x'
then delete x' (a leaf)
•When x has two children,
then find x's successor z (which has no left child)
then replace x's contents with z's contents, and
delete z
02-02-2023
Department of Computer Science and Engineering
CASE 1
60
20 70
10 40 65 85
5 15 30 50 80 90
55
02-02-2023 129
Department of Computer Science and Engineering
CASE 2
60
20 70
10 40 65 85
5 15 30 50 80 90
55
02-02-2023 130
Department of Computer Science and Engineering
CASE 2
60
20 70
10 40 65 85
5 15 30
50 80 90
55
02-02-2023 131
Department of Computer Science and Engineering
CASE 3
60
20 70
10 40 65 85
5 15 30 50 80 90
55
prev
02-02-2023 132
Department of Computer Science and Engineering
CASE 3
55
20 70
10 40 65 85
5 15 30 50 80 90
02-02-2023 133
Department of Computer Science and Engineering 134
DELETION
AVL_DELETE(T, n)
p = n
while p != NULL
p->height = 1 + MAX(HEIGHT(p->left), HEIGHT(p->right))
if(BALANCE_FACTOR(p) <= -2 || balance_factor(p) >= 2)
x = p
if x->left->height > x->right->height
y = x->left
else
y = x->right
02-02-2023
Department of Computer Science and Engineering 135
DELETION
if y->left->height > y->right->height
z = y->left
else if y->left->height < y->right->height
z = y->right
else
if y == x->left
z = y->left
else
z = y->right
if y == x->left
if z == x->left->left //case1
RIGHT_ROTATE(T, x)
02-02-2023
Department of Computer Science and Engineering 136
DELETION
else if z == x->left->right //case 3
LEFT_ROTATE(T, y)
RIGHT_ROTATE(T, x)
else if y == x->right
if z == x->right->right //case 2
LEFT_ROTATET(T, x)
else if z == x->right->left //case 4
RIGHT_ROTATE(T, y)
LEFT_ROTATE(T, x)
p = p->parent
02-02-2023
Department of Computer Science and Engineering 137
ANALYSIS
02-02-2023
Department of Computer Science and Engineering 138
ADVANTAGES & DISADVANTAGES
ADVANTAGES
• self sorting binary trees
• It is highly efficient when there is a large number of input data which
involves a lot of insertions.
DISADVANTAGES
• The code for AVL tree is much more complex than the code for BST and
we have to handle a lot of corner cases.
• Deletion operations cost high in AVL trees as they involve a lot of
pointer changes and rotations.
• Increase the pointer overhead which even tends to some negligiable extra
space for very big inputs.
02-02-2023
Department of Computer Science and Engineering 139
APPLICATIONS
• Particularly used for look up intensive applications for
example it is used for indexing large records in database to
improve search
• Used for all sorts of in-memory collections such as sets and
dictionaries.
• Used in Memory management subsystem of linux kernel to
search memory regions of processes during preemption.
02-02-2023
Department of Computer Science and Engineering 140
APPLICATIONS
02-02-2023
Thank You
Department of Computer Science and Engineering

More Related Content

Similar to unit ii.pptx

Introduction.ppt
Introduction.pptIntroduction.ppt
Introduction.ppt
backlinkspuro
 
R-Trees and Geospatial Data Structures
R-Trees and Geospatial Data StructuresR-Trees and Geospatial Data Structures
R-Trees and Geospatial Data Structures
Amrinder Arora
 
Binary tree and operations
Binary tree and operations Binary tree and operations
Binary tree and operations
varagilavanya
 
FDS_dept_ppt.pptx
FDS_dept_ppt.pptxFDS_dept_ppt.pptx
FDS_dept_ppt.pptx
SatyajitPatil42
 
DSU summer 19.pdf
DSU summer 19.pdfDSU summer 19.pdf
DSU summer 19.pdf
SohamKotalwar1
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
Meghaj Mallick
 
B.Tech.AIDS syllabus anna university .pdf
B.Tech.AIDS syllabus anna university .pdfB.Tech.AIDS syllabus anna university .pdf
B.Tech.AIDS syllabus anna university .pdf
AishwaryaGiridev
 
B.Tech.AIDS 2017 regulation annauniversity .pdf
B.Tech.AIDS 2017 regulation annauniversity .pdfB.Tech.AIDS 2017 regulation annauniversity .pdf
B.Tech.AIDS 2017 regulation annauniversity .pdf
AishwaryaGiridev
 
Tree Operations
Tree OperationsTree Operations
Tree Operations
Asadullah Tareen
 
Normalization
NormalizationNormalization
Normalization
Dr. C.V. Suresh Babu
 
DSA IV Unit.pptx
DSA IV Unit.pptxDSA IV Unit.pptx
DSA IV Unit.pptx
AyeshaTakreem1
 
Binary Tree and jsksjshddjdjdkdkdjdjdjfjckck
Binary Tree and jsksjshddjdjdkdkdjdjdjfjckckBinary Tree and jsksjshddjdjdkdkdjdjdjfjckck
Binary Tree and jsksjshddjdjdkdkdjdjdjfjckck
rahulrudhand2003
 
Modern Database Systems - Lecture 02
Modern Database Systems - Lecture 02Modern Database Systems - Lecture 02
Modern Database Systems - Lecture 02
Michael Mathioudakis
 
module1:Introduction to digital electronics
module1:Introduction to digital electronicsmodule1:Introduction to digital electronics
module1:Introduction to digital electronics
chandrakant shinde
 
Cynthia Professional Prortfolio
Cynthia Professional PrortfolioCynthia Professional Prortfolio
Cynthia Professional PrortfolioCynthia Eichner
 
stack & queues .pptx
stack & queues .pptxstack & queues .pptx
stack & queues .pptx
kaishsahu
 
1 unit- PPT - SS22-23.pptx
1 unit- PPT - SS22-23.pptx1 unit- PPT - SS22-23.pptx
1 unit- PPT - SS22-23.pptx
inian2
 
Technical Drafting Module 5
Technical Drafting Module 5Technical Drafting Module 5
Technical Drafting Module 5
DepEd
 
Introduction to Epistemic Network Analysis
Introduction to Epistemic Network AnalysisIntroduction to Epistemic Network Analysis
Introduction to Epistemic Network Analysis
Vitomir Kovanovic
 

Similar to unit ii.pptx (20)

Introduction.ppt
Introduction.pptIntroduction.ppt
Introduction.ppt
 
R-Trees and Geospatial Data Structures
R-Trees and Geospatial Data StructuresR-Trees and Geospatial Data Structures
R-Trees and Geospatial Data Structures
 
A41001011
A41001011A41001011
A41001011
 
Binary tree and operations
Binary tree and operations Binary tree and operations
Binary tree and operations
 
FDS_dept_ppt.pptx
FDS_dept_ppt.pptxFDS_dept_ppt.pptx
FDS_dept_ppt.pptx
 
DSU summer 19.pdf
DSU summer 19.pdfDSU summer 19.pdf
DSU summer 19.pdf
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
B.Tech.AIDS syllabus anna university .pdf
B.Tech.AIDS syllabus anna university .pdfB.Tech.AIDS syllabus anna university .pdf
B.Tech.AIDS syllabus anna university .pdf
 
B.Tech.AIDS 2017 regulation annauniversity .pdf
B.Tech.AIDS 2017 regulation annauniversity .pdfB.Tech.AIDS 2017 regulation annauniversity .pdf
B.Tech.AIDS 2017 regulation annauniversity .pdf
 
Tree Operations
Tree OperationsTree Operations
Tree Operations
 
Normalization
NormalizationNormalization
Normalization
 
DSA IV Unit.pptx
DSA IV Unit.pptxDSA IV Unit.pptx
DSA IV Unit.pptx
 
Binary Tree and jsksjshddjdjdkdkdjdjdjfjckck
Binary Tree and jsksjshddjdjdkdkdjdjdjfjckckBinary Tree and jsksjshddjdjdkdkdjdjdjfjckck
Binary Tree and jsksjshddjdjdkdkdjdjdjfjckck
 
Modern Database Systems - Lecture 02
Modern Database Systems - Lecture 02Modern Database Systems - Lecture 02
Modern Database Systems - Lecture 02
 
module1:Introduction to digital electronics
module1:Introduction to digital electronicsmodule1:Introduction to digital electronics
module1:Introduction to digital electronics
 
Cynthia Professional Prortfolio
Cynthia Professional PrortfolioCynthia Professional Prortfolio
Cynthia Professional Prortfolio
 
stack & queues .pptx
stack & queues .pptxstack & queues .pptx
stack & queues .pptx
 
1 unit- PPT - SS22-23.pptx
1 unit- PPT - SS22-23.pptx1 unit- PPT - SS22-23.pptx
1 unit- PPT - SS22-23.pptx
 
Technical Drafting Module 5
Technical Drafting Module 5Technical Drafting Module 5
Technical Drafting Module 5
 
Introduction to Epistemic Network Analysis
Introduction to Epistemic Network AnalysisIntroduction to Epistemic Network Analysis
Introduction to Epistemic Network Analysis
 

Recently uploaded

Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
Bisnar Chase Personal Injury Attorneys
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
goswamiyash170123
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
AG2 Design
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Landownership in the Philippines under the Americans-2-pptx.pptx
Landownership in the Philippines under the Americans-2-pptx.pptxLandownership in the Philippines under the Americans-2-pptx.pptx
Landownership in the Philippines under the Americans-2-pptx.pptx
JezreelCabil2
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 

Recently uploaded (20)

Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Landownership in the Philippines under the Americans-2-pptx.pptx
Landownership in the Philippines under the Americans-2-pptx.pptxLandownership in the Philippines under the Americans-2-pptx.pptx
Landownership in the Philippines under the Americans-2-pptx.pptx
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 

unit ii.pptx

  • 1. Department of Computer Science and Engineering DATA STRUCTURES School of Computing Vel Tech Rangarajan Dr. Sagunthala R&D Institute of Science and Technology Year : 2019-23 Course Code : 1151CS102 Course Category : Program Core Unit No : II Topic : Trees Faculty Name : Mrs.A.SANGEETHA
  • 2. Department of Computer Science and Engineering COURSE DETAILS 02-02-2023 2 and Project Management (SEPM) Preamble: This course provides an introduction to the basic concepts and techniques of Linear and nonlinear data Structures and Analyze the various algorithm. 1150CS201 Problem Solving using C •Prerequisite Courses: Sl. No Course Code Course Name 1 1151CS105 System Software 2 1151CS106 Design and Analysis of Algorithm 3 1151CS107 Database Management System 4 1151CS108 Operating Systems 5 1151CS111 Computer Networks •Related Courses:
  • 3. Department of Computer Science and Engineering COURSE OUTCOMES 02-02-2023 3  Identify and explain user defined data types, linear data structures for solving real world problems.  Design modular programs on non linear data structures and algorithms for solving engineering problems efficiently.  Illustrate special trees and Hashing Techniques.  Apply searching techniques in graph traversal  Apply sorting techniques for real world problems.
  • 4. Department of Computer Science and Engineering AGENDA 02-02-2023 4 and Project Management (SEPM)  Introduction to trees  Tree  Binary Trees  Definitions  Expression Tree  Binary Tree Traversals  The Search Tree ADT  Binary Search Trees  AVL Tree.
  • 5. Department of Computer Science and Engineering 5 NON LINEAR DATA STRUCTURES •Data elements are not arranged sequentially or linearly •Supports multi-level storage Tree Graph 02-02-2023
  • 6. Department of Computer Science and Engineering 6 COMPARISON 02-02-2023
  • 7. Department of Computer Science and Engineering 7 TREE • Tree is a hierarchical data structure which stores the information naturally in the form of hierarchy style • Collection of nodes (starting at a root node) together with a list of references to nodes (the "children") 02-02-2023
  • 8. Department of Computer Science and Engineering 8 WHY? organize all of their recordsintoa computerdatabase.  The first thing you are asked to do is create a database of names withall thecompany'smanagement and employees.  T ostart yourwork,youmakea listof everyoneinthe companyalong withtheir positionandother details.  Imagine that you are hired by company XYZ to 02-02-2023
  • 9. Department of Computer Science and Engineering 9 WHY? EmployeesTable 02-02-2023
  • 10. Department of Computer Science and Engineering 10 WHY? EmployeesTable 02-02-2023
  • 11. Department of Computer Science and Engineering 11 TERMINOLOGIES 02-02-2023
  • 12. Department of Computer Science and Engineering 12 TERMINOLOGIES 1. Root- •The first node from where the tree originates is called as a root node. •Doesn’t have parent node 02-02-2023
  • 13. Department of Computer Science and Engineering 13 TERMINOLOGIES 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. 02-02-2023
  • 14. Department of Computer Science and Engineering 14 TERMINOLOGIES 3. Parent- •The node which has a branch from it to any other node is called as a parent node. •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. 02-02-2023
  • 15. Department of Computer Science and Engineering 15 TERMINOLOGIES 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. 02-02-2023
  • 16. Department of Computer Science and Engineering 16 TERMINOLOGIES 5. Siblings- •Nodes which belong to the same parent are called as siblings. •In other words, nodes with the same parent are sibling nodes. 02-02-2023
  • 17. Department of Computer Science and Engineering 17 TERMINOLOGIES 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. 02-02-2023
  • 18. Department of Computer Science and Engineering 18 TERMINOLOGIES 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. 02-02-2023
  • 19. Department of Computer Science and Engineering 19 TERMINOLOGIES 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. 02-02-2023
  • 20. Department of Computer Science and Engineering 20 TERMINOLOGIES 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. 02-02-2023
  • 21. Department of Computer Science and Engineering 21 TERMINOLOGIES 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 02-02-2023
  • 22. Department of Computer Science and Engineering 22 TERMINOLOGIES 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 02-02-2023
  • 23. Department of Computer Science and Engineering 23 TERMINOLOGIES 12. Subtree- •In a tree, each child from a node forms a subtree recursively. •Every child node forms a subtree on its parent node. 02-02-2023
  • 24. Department of Computer Science and Engineering 24 TERMINOLOGIES 12. Subtree- •In a tree, each child from a node forms a subtree recursively. •Every child node forms a subtree on its parent node. 02-02-2023
  • 25. Department of Computer Science and Engineering 25 EXAMPLE 02-02-2023
  • 26. Department of Computer Science and Engineering 26 REPRESENTATION •List Representation •Left Child - Right Sibling Representation 02-02-2023
  • 27. Department of Computer Science and Engineering 27 REPRESENTATION - EXAMPLE 02-02-2023
  • 28. Department of Computer Science and Engineering 28 LIST REPRESENTATION 02-02-2023
  • 29. Department of Computer Science and Engineering 29 LEFT CHILD RIGHT SIBLING 02-02-2023
  • 30. Department of Computer Science and Engineering 30 BINARY TREE A binary tree is a tree where all nodes have zero, oneor two children  A binary tree is either: — an empty tree — consists of a node, called a root, and zero, one, ortwo children (left and right), each of which are themselves binary trees  Every non-empty node has two children, either of which may be empty 02-02-2023
  • 31. Department of Computer Science and Engineering 31 BINARY TREE 02-02-2023
  • 32. Department of Computer Science and Engineering 32 BINARY TREE 02-02-2023
  • 33. Department of Computer Science and Engineering 33 TREE VS BINARY TREE 02-02-2023
  • 34. Department of Computer Science and Engineering 34 REPRESENTATION Array Representation Linked List Representation 02-02-2023
  • 35. Department of Computer Science and Engineering 35 ARRAY REPRESENTATION • Array representation – The root of the tree is stored in position 0. – The node in position i, is the implicit father of nodes 2i+1 and 2i+2. – Left child is at 2i+1 and right at 2i+2. 02-02-2023
  • 36. Department of Computer Science and Engineering 36 ARRAY REPRESENTATION X Y Z A B C 0 1 2 3 4 5 6 7 8 10 12 X Y Z A B C 9 11 02-02-2023
  • 37. Department of Computer Science and Engineering 37 LINKED LIST REPRESENTATION • Every node will consists of information, and two pointers left and right pointing to the left and right child nodes. struct node { int data; struct node *left; struct node *right; }; B A D C 02-02-2023
  • 38. Department of Computer Science and Engineering 38 TYPES Full binary tree: Every node other than leaf nodes has 2 child nodes. Complete binary tree: All levels are filled except possibly the last one, and all nodes are filled in as far left as possible. Perfect binary tree: All nodes have two children and all leaves are at the same level. 02-02-2023
  • 39. Department of Computer Science and Engineering 39 TYPES FULL BINARY TREE PERFECT BINARY TREE COMPLETE BINARY TREE 02-02-2023
  • 40. Department of Computer Science and Engineering 40 •Binary tree in which the leaf nodes are operands and the interior nodes are operators. EXPRESSION TREE 02-02-2023
  • 41. Department of Computer Science and Engineering 41 Constructing an Expression Tree Steps : 1. Read one symbol at a time from the postfix expression. 2. Check whether the symbol is an operand or operator. (a) If the symbol is an operand, create a one - node tree and push a pointer on to the stack. (b) If the symbol is an operator pop two pointers from the stack namely T1 and T2 and form a new tree with root as the operator and T2 as a left child and T1 as a right child. A pointer to this new tree is then pushed onto the stack. EXPRESSION TREE 02-02-2023
  • 42. Department of Computer Science and Engineering 42 EXPRESSION TREE A*(B-C) + (D+E) 02-02-2023
  • 43. Department of Computer Science and Engineering 43 EXPRESSION TREE-PROBLEM A+B*(C/D)^E%F 02-02-2023
  • 44. Department of Computer Science and Engineering BINARY SEARCH TREE 02-02-2023 44 and Project Management (SEPM) • Binary tree in which for every node X in the tree, • keys in its left subtree < the key value in X • keys in its right subtree > key value in X.
  • 45. Department of Computer Science and Engineering BINARY SEARCH TREE 02-02-2023 45 and Project Management (SEPM) • Binary tree in which for every node X in the tree, • keys in its left subtree < the key value in X • keys in its right subtree > key value in X.
  • 46. Department of Computer Science and Engineering DEFINITION 02-02-2023 46 and Project Management (SEPM) A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties −  The value of the key of the left sub-tree is less than the value of its parent (root) node's key.  The value of the key of the right sub-tree is greater than or equal to the value of its parent (root) node's key. USE: used to construct more abstract data structures such as sets, multisets, and associative arrays.
  • 47. Department of Computer Science and Engineering BINARY SEARCH TREE - CONSTRUCTION 02-02-2023 47 and Project Management (SEPM) Construct a Binary Search Tree (BST) for the following sequence of numbers- 50, 70, 60, 20, 90 • When elements are given in a sequence, • Always consider the first element as the root node. Consider the given elements and insert them in the BST one by one.
  • 48. Department of Computer Science and Engineering BINARY SEARCH TREE - CONSTRUCTION 02-02-2023 48 and Project Management (SEPM) Insert 50
  • 49. Department of Computer Science and Engineering BINARY SEARCH TREE - CONSTRUCTION 02-02-2023 49 and Project Management (SEPM) Insert 70 As 70 > 50, so insert 70 to the right of 50.
  • 50. Department of Computer Science and Engineering BINARY SEARCH TREE - CONSTRUCTION 02-02-2023 50 and Project Management (SEPM) Insert 60 As 60 > 50, so insert 60 to the right of 50. As 60 < 70, so insert 60 to the left of 70
  • 51. Department of Computer Science and Engineering BINARY SEARCH TREE - CONSTRUCTION 02-02-2023 51 and Project Management (SEPM) Insert 20 As 20 < 50, so insert 20 to the left of 50.
  • 52. Department of Computer Science and Engineering BINARY SEARCH TREE - CONSTRUCTION 02-02-2023 52 and Project Management (SEPM) Insert 90 As 90 > 50, so insert 90 to the right of 50. As 90 > 70, so insert 90 to the right of 70.
  • 53. Department of Computer Science and Engineering DECLARATION 02-02-2023 53 and Project Management (SEPM) Struct TreeNode; typedef struct TreeNode * SearchTree; SearchTree Insert (int X, SearchTree T); SearchTree Delete (int X, SearchTree T); int Find (int X, SearchTree T); int FindMin (Search Tree T); int FindMax (SearchTree T); SearchTree MakeEmpty (SearchTree T); Struct TreeNode { int Element ; SearchTree Left; SearchTree Right; };
  • 54. Department of Computer Science and Engineering MAKE EMPTY 02-02-2023 54 and Project Management (SEPM) SearchTree MakeEmpty (SearchTree T) { if (T! = NULL) { MakeEmpty (T left); MakeEmpty (T Right); free (T); } return NULL ; }
  • 55. Department of Computer Science and Engineering INSERTION - ALGORITHM 02-02-2023 55 and Project Management (SEPM) Step 1 - Create a newNode with given value and set its left and right to NULL. Step 2 - Check whether tree is Empty. Step 3 - If the tree is Empty, then set root to newNode. Step 4 - If the tree is Not Empty, then check whether the value of newNode is smaller or larger than the node (here it is root node). Step 5 - If newNode is smaller than or equal to the node then move to its left child. If newNode is larger than the node then move to its right child.
  • 56. Department of Computer Science and Engineering INSERTION - ALGORITHM 02-02-2023 56 and Project Management (SEPM) Step 6- Repeat the above steps until we reach to the leaf node (i.e., reaches to NULL). Step 7 - After reaching the leaf node, insert the newNode as left child if the newNode is smaller or equal to that leaf node or else insert it as right child.
  • 57. Department of Computer Science and Engineering INSERTION 02-02-2023 57 and Project Management (SEPM) SearchTree Insert (int X, searchTree T) if (T = = NULL) T = malloc (size of (Struct TreeNode)); if (T! = NULL) T →Element = X; T→ left = NULL; T →Right = NULL; else if (X < T →Element) T → left = Insert (X, T →left) else if (X > T →Element) T → Right = Insert (X, T →Right) return T
  • 58. Department of Computer Science and Engineering INSERTION - EXAMPLE 02-02-2023 58 and Project Management (SEPM)
  • 59. Department of Computer Science and Engineering INSERTION - EXAMPLE 02-02-2023 59 and Project Management (SEPM)
  • 60. Department of Computer Science and Engineering FIND - ALGORITHM 02-02-2023 60 and Project Management (SEPM) Step 1 - Read the search element from the user. Step 2 - Compare the search element with the 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 node value. Step 5 - If search element is smaller, then continue the search process in left subtree.
  • 61. Department of Computer Science and Engineering FIND - ALGORITHM 02-02-2023 61 and Project Management (SEPM) Step 6- If search element is larger, then continue the search process in right subtree. Step 7 - Repeat the same until we find the exact element or until the search element is compared with the leaf node Step 8 - If we reach to the node having the value equal to the search value then display "Element is found" and terminate the function. Step 9 - If we reach to the leaf node and if it is also not matched with the search element, then display "Element is not found" and terminate the function.
  • 62. Department of Computer Science and Engineering FIND 02-02-2023 62 and Project Management (SEPM) Find (int X, SearchTree T) if T = = NULL return NULL if (X < T → Element) return Find (X, T →left); else If (X > T→ Element) return Find (X, T →Right) else return T
  • 63. Department of Computer Science and Engineering FIND MIN 02-02-2023 63 and Project Management (SEPM) •returns the position of the smallest element in the tree. RECURISVE ROUTINE FOR FINDMIN FindMin (SearchTree T) if (T = = NULL) return NULL else if (T →left = = NULL) return T else return FindMin (T → left)
  • 64. Department of Computer Science and Engineering FIND MIN – NON RECURSIVE 02-02-2023 64 and Project Management (SEPM) FindMin (SearchTree T) if (T! = NULL) while (T →Left ! = NULL) T = T →Left ; return T
  • 65. Department of Computer Science and Engineering FIND MAX 02-02-2023 65 and Project Management (SEPM) •return the position of largest elements in the tree. RECURISVE ROUTINE FOR FINDMAX FindMax (SearchTree T) if T is NULL return NULL else if T →Right = = NULL return T else FindMax (T →Right); }
  • 66. Department of Computer Science and Engineering FIND MAX– NON RECURSIVE 02-02-2023 66 and Project Management (SEPM) int FindMax (SearchTree T) if (T! = NULL) while (T Right ! = NULL) T = T →Right ; return T ;
  • 67. Department of Computer Science and Engineering DELETION 02-02-2023 67 and Project Management (SEPM) To delete an element, consider the following three possibilities. • CASE 1 Node to be deleted is a leaf node (ie) No children. • CASE 2 Node with one child. • CASE 3 Node with two children.
  • 68. Department of Computer Science and Engineering CASE 1 ALGORITHM 02-02-2023 68 and Project Management (SEPM) Deleting a leaf node Step 1 Find the node to be deleted using search operation Step 2 Delete the node using free function (If it is a leaf) and terminate the function.
  • 69. Department of Computer Science and Engineering CASE 1 EXAMPLE 02-02-2023 69 and Project Management (SEPM)
  • 70. Department of Computer Science and Engineering CASE 2 ALGORITHM 02-02-2023 70 and Project Management (SEPM) Deleting a node with one child Step 1 - Find the node to be deleted using search operation Step 2 - If it has only one child then create a link between its parent node and child node. Step 3 - Delete the node using free function and terminate the function.
  • 71. Department of Computer Science and Engineering CASE 2 EXAMPLE 02-02-2023 71 and Project Management (SEPM)
  • 72. Department of Computer Science and Engineering CASE 3 ALGORITHM 02-02-2023 72 and Project Management (SEPM) Deleting a node with two children Step 1 - Find the node to be deleted using search operation Step 2 - If it has two children, then find the largest node in its left subtree (OR) the smallest node in its right subtree. Step 3 - Swap both deleting node and node which is found in the above step. Step 4 - Then check whether deleting node came to case 1 or case 2 or else goto step 2 Step 5 - If it comes to case 1, then delete using case 1 logic. Step 6- If it comes to case 2, then delete using case 2 logic. Step 7 - Repeat the same process until the node is deleted from the tree.
  • 73. Department of Computer Science and Engineering CASE 3 EXAMPLE 02-02-2023 73 and Project Management (SEPM) Taking the smallest node in its right subtree
  • 74. Department of Computer Science and Engineering CASE 3 EXAMPLE 02-02-2023 74 and Project Management (SEPM) Taking the largest node in its left subtree
  • 75. Department of Computer Science and Engineering DELETION 02-02-2023 75 and Project Management (SEPM) SearchTree Delete (X, T) Declare Tmpcell ; if (T = = NULL) Error ("Element not found") else if (X < T →Element) T →Left = Delete (X, T Left) else if (X > T Element) T →Right = Delete (X, T →Right)
  • 76. Department of Computer Science and Engineering DELETION 02-02-2023 76 and Project Management (SEPM) else // Two children if (T→ Left && T→ Right) // Replace with smallest data in right subtree Tmpcell = FindMin (T→ Right) T →Element = Tmpcell → Element T →Right = Delete (T → Element; T →Right)
  • 77. Department of Computer Science and Engineering DELETION 02-02-2023 77 and Project Management (SEPM) else // one or zero children Tmpcell = T if (T →Left = = NULL) T = T→ Right else if (T→ Right = = NULL) T = T →Left free (TmpCell) return T
  • 78. Department of Computer Science and Engineering EXAMPLE 02-02-2023 78 and Project Management (SEPM)
  • 79. Department of Computer Science and Engineering TREE TRAVERSAL 02-02-2023 79 and Project Management (SEPM) The process of visiting (checking and/or updating) each node in a tree data structure
  • 80. Department of Computer Science and Engineering 80 TYPES In order traversal Pre order traversal Post order traversal 02-02-2023
  • 81. Department of Computer Science and Engineering 81 IN ORDER TRAVERSAL • Process all nodes of a tree by recursively processing the left subtree, then processing the root, and finally the right subtree 02-02-2023
  • 82. Department of Computer Science and Engineering 82 ALGORITHM Algorithm Inorder(tree) 1. Traverse the left subtree, i.e., call Inorder(left-subtree) 2. Visit the root. 3. Traverse the right subtree, i.e., call Inorder(right-subtree) 02-02-2023
  • 83. Department of Computer Science and Engineering 83 PSEUDOCODE - RECURSIVE inorder(node) if (node == null) return inorder(node.left) visit(node) inorder(node.right) 02-02-2023
  • 84. Department of Computer Science and Engineering 84 PSEUDOCODE - ITERATIVE iterativeInorder(node) s ← empty stack while (not s.isEmpty() or node ≠ null) if (node ≠ null) s.push(node) node ← node.left else node ← s.pop() visit(node) node ← node.right 02-02-2023
  • 85. Department of Computer Science and Engineering 85 EXAMPLE 02-02-2023
  • 86. Department of Computer Science and Engineering 86 EXAMPLE 02-02-2023
  • 87. Department of Computer Science and Engineering 87 PRE ORDER TRAVERSAL Preorder traversal of a binary tree is defined as follow  Process the root node  Traverse the left subtree in preorder  Traverse the right subtree in preorder If particular subtree is empty (i.e., node has no left or right descendant) the traversal is performed by doing nothing, In other words, a null subtree is considered to be fully traversed when it is encountered. 02-02-2023
  • 88. Department of Computer Science and Engineering 88 ALGORITHM Algorithm Preorder(tree) 1. Visit the root. 2. Traverse the left subtree, i.e., call Preorder(left-subtree) 3. Traverse the right subtree, i.e., call Preorder(right-subtree) 02-02-2023
  • 89. Department of Computer Science and Engineering 89 PSEUDOCODE - RECURSIVE preorder(node) if (node == null) return visit(node) preorder(node.left) preorder(node.right) 02-02-2023
  • 90. Department of Computer Science and Engineering 90 PSEUDOCODE - ITERATIVE iterativePreorder(node) if (node == null) return s ← empty stack s.push(node) while (not s.isEmpty()) node ← s.pop() visit(node) if node.right ≠ null s.push(node.right) if node.left ≠ null s.push(node.left) 02-02-2023
  • 91. Department of Computer Science and Engineering 91 EXAMPLE 02-02-2023
  • 92. Department of Computer Science and Engineering 92 EXAMPLE 02-02-2023
  • 93. Department of Computer Science and Engineering 93 POST ORDER 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. 02-02-2023
  • 94. Department of Computer Science and Engineering 94 ALGORITHM Algorithm Postorder(tree) 1. Traverse the left subtree, i.e., call Postorder(left-subtree) 2. Traverse the right subtree, i.e., call Postorder(right-subtree) 3. Visit the root. 02-02-2023
  • 95. Department of Computer Science and Engineering 95 PSEUDOCODE - RECURSIVE postorder(node) if (node == null) return postorder(node.left) postorder(node.right) visit(node) 02-02-2023
  • 96. Department of Computer Science and Engineering 96 PSEUDOCODE - ITERATIVE iterativePostorder(node) s ← empty stack lastNodeVisited ← null while (not s.isEmpty() or node ≠ null) if (node ≠ null) s.push(node) node ← node.left else peekNode ← s.peek if (peekNode.right ≠ null and lastNodeVisited ≠ peekNode.right) node ← peekNode.right else visit(peekNode) lastNodeVisited ← s.pop() 02-02-2023
  • 97. Department of Computer Science and Engineering 97 EXAMPLE 02-02-2023
  • 98. Department of Computer Science and Engineering 98 EXAMPLE 02-02-2023
  • 99. Department of Computer Science and Engineering 99 ILLUSTRATION • Assume: visiting a node is printing its label • Preorder: 1 3 5 4 6 7 8 9 10 11 12 • Inorder: 4 5 6 3 1 8 7 9 11 10 12 • Postorder: 4 6 5 3 8 11 12 10 9 7 1 1 3 11 9 8 4 6 5 7 1 2 1 0 02-02-2023
  • 100. Department of Computer Science and Engineering 100 PROBLEM 02-02-2023
  • 101. Department of Computer Science and Engineering 101 APPLICATION •In-order traversal is very commonly used on binary search trees because it returns values from the underlying set in order, according to the comparator that set up the binary search tree. •Post-order traversal while deleting or freeing nodes and values can delete or free an entire binary tree. •Expression Tree 02-02-2023
  • 102. Department of Computer Science and Engineering AVL TREE - AGENDA 02-02-2023 102 and Project Management (SEPM) •Drawbacks of BST •Balanced Binary Trees •What is AVL Tree? •Characteristics •Operations •Implementation •Advantages &Disadvantages •Applications
  • 103. Department of Computer Science and Engineering DRAWBACKS OF BST 02-02-2023 103 and Project Management (SEPM) ● The disadvantage of a binary search tree is that its height can be as large as N-1 ● Worst case running time is O(N) ■ What happens when you Insert elements in ascending order? ○ Insert: 2, 4, 6, 8, 10, 12 into an empty BST ■ Problem: Lack of “balance”: ○ compare depths of left and right subtree ■ Unbalanced degenerate tree
  • 104. Department of Computer Science and Engineering 104 BALANCED VS UNBALANCED BST 02-02-2023
  • 105. Department of Computer Science and Engineering 105 APPROACHES TO BALANCING TREES ● Don't balance ■ May end up with some nodes very deep ● Strict balance ■ The tree must always be balanced perfectly ● Pretty good balance ■ Only allow a little out of balance ● Adjust on access ■ Self-adjusting 02-02-2023
  • 106. Department of Computer Science and Engineering 106 AVL TREE Adelson-Velskii and Landis  for each node, the height of the left and right subtrees can differ at most 1,-1,0. Binary search tree with balance condition in which the sub- trees of each node can differ by at most 1 in their height 02-02-2023
  • 107. Department of Computer Science and Engineering 107 AVL TREE AVL property violated here AVL tree 02-02-2023
  • 108. Department of Computer Science and Engineering 108 CHARACTERISTICS • Each node can hold a maximum of two child nodes. • Each node can carry only one key value. • The height of the child nodes of any time must differ in height by no more than 1. • When there is a difference in height of more than 1 or less than -1 between the child nodes of a particular node, the tree goes through the process of rebalancing through a series of rotations until it is re-balanced. 02-02-2023
  • 109. Department of Computer Science and Engineering 109 MINNIMUM NO OF NODES N1 = 2 N2 =4 N3 = N2+N1+1=7 N0 = 1 ■ N(h) = minimum number of nodes in anAVL tree of height h ■ N(h) = N(h-1) + N(h-2) + 1 02-02-2023
  • 110. Department of Computer Science and Engineering 110 OPERATIONS •INSERTION •DELETION •SEARCH 02-02-2023
  • 111. Department of Computer Science and Engineering 111 BALANCE FACTOR BF= height of left subtree– height of right subtree 02-02-2023
  • 112. Department of Computer Science and Engineering 112 NODE DECLARATION struct Node { int key; struct Node *left; struct Node *right; int height; }; 02-02-2023
  • 113. Department of Computer Science and Engineering 113 INSERTION • Insert will be done recursively • the insert call will return true if the height of the sub-tree has changed • if insert() returns true, balance factor of current node needs to be adjusted ○ balance factor = height(left) – height(right) • if balance factor equals 2 for any node, the sub- tree must be rebalanced 02-02-2023
  • 114. Department of Computer Science and Engineering 114 ALGORITHM Step 1: First, insert a new element into the tree using BST's (Binary Search Tree) insertion logic. Step 2: After inserting the elements you have to check the Balance Factor of each node. Step 3: When the Balance Factor of every node will be found like 0 or 1 or -1 then the algorithm will proceed for the next operation. Step 4: When the balance factor of any node comes other than the above three values then the tree is said to be imbalanced. Then perform the suitable Rotation to make it balanced and then the algorithm will proceed for the next operation. 02-02-2023
  • 115. Department of Computer Science and Engineering 115 REBALANCING ● To check if a tree needs to be rebalanced ■ start at the parent of the inserted node and journey up the tree to the root ○ if a node’s balance factor becomes 2 need to do a rotation in the sub-tree rooted at the node ○ once sub-tree has been re-balanced, guaranteed that the rest of the tree is balanced as well  can just return false from the insert() method ■ 4 possible cases for re-balancing 02-02-2023
  • 116. Department of Computer Science and Engineering 116 POSSIBLE CASES There are 4 cases: Outside Cases (require single rotation) : 1. Insertion into left subtree of left child of node A 2. Insertion into right subtree of right child of node A Inside Cases (require double rotation) : 3. Insertion into right subtree of left child of node A 4. Insertion into left subtree of right child of node A 02-02-2023
  • 117. Department of Computer Science and Engineering 117 CASE1-RIGHT ROTATION 02-02-2023
  • 118. Department of Computer Science and Engineering 118 CASE 2 – LEFT ROTATION 02-02-2023
  • 119. Department of Computer Science and Engineering 119 LEFT & RIGHT ROTATIONS 02-02-2023
  • 120. Department of Computer Science and Engineering 120 CASE 3 – RIGHT SUBTREE LEFT CHILD 02-02-2023
  • 121. Department of Computer Science and Engineering 121 CASE 4 – LEFTSUBTREE RIGHT CHILD 02-02-2023
  • 122. Department of Computer Science and Engineering 122 INSERTION - EXAMPLE 02-02-2023
  • 123. Department of Computer Science and Engineering 123 INSERTION INSERT(T, n) temp = T->root y = NULL while temp != NULL y = temp if n->data < temp->data temp = temp->left else temp = temp->right n->parent = y if y==NULL T->root = n 02-02-2023
  • 124. Department of Computer Science and Engineering 124 else if n->data < y->data y->left = n else y->right = n z = n while y != NULL y->height = 1 + MAX(HEIGHT(y->left), HEIGHT(y->right)) x = y->parent if BALANCE-FACTOR(x) <= -2 or BALANCE-FACTOR(x) >= 2 if y == x->left if z == x->left->left //case1 RIGHT_ROTATE(T, x) INSERTION 02-02-2023
  • 125. Department of Computer Science and Engineering 125 else if z == x.left.right //case 3 LEFT_ROTATE(T, y) RIGHT_ROTATE(T, x) else if y == x->right if z == x->right->right //case 2 LEFT_ROTATET(T, x) else if z == x->right->left //case 4 RIGHT_ROTATE(T, y) LEFT_ROTATE(T, x) break y = y->parent z = z->parent INSERTION 02-02-2023
  • 126. Department of Computer Science and Engineering 126 SEARCH ● Searching an AVL tree is exactly the same as searching a regular binary tree ■ all descendants to the right of a node are greater than the node ■ all descendants to the left of a node are less than the node 02-02-2023
  • 127. Department of Computer Science and Engineering 127 SEARCH SEARCH(x, T) if(T->root != null) if(T->root->data == x) return r else if(T->root->data > x) return SEARCH(x, T->root->left) else return SEARCH(x, T->root->right) 02-02-2023
  • 128. Department of Computer Science and Engineering 128 DELETION -ALGORITHM Step 1: First, find that node where k is stored Step 2: Delete those contents of the node (Suppose the node is x) Step 3: Claim: Deleting a node in an AVL tree can be reduced by deleting a leaf. There are three possible cases: •When x has no children then, delete x •When x has one child, let x' becomes the child of x. then replace the contents of x with the contents of x' then delete x' (a leaf) •When x has two children, then find x's successor z (which has no left child) then replace x's contents with z's contents, and delete z 02-02-2023
  • 129. Department of Computer Science and Engineering CASE 1 60 20 70 10 40 65 85 5 15 30 50 80 90 55 02-02-2023 129
  • 130. Department of Computer Science and Engineering CASE 2 60 20 70 10 40 65 85 5 15 30 50 80 90 55 02-02-2023 130
  • 131. Department of Computer Science and Engineering CASE 2 60 20 70 10 40 65 85 5 15 30 50 80 90 55 02-02-2023 131
  • 132. Department of Computer Science and Engineering CASE 3 60 20 70 10 40 65 85 5 15 30 50 80 90 55 prev 02-02-2023 132
  • 133. Department of Computer Science and Engineering CASE 3 55 20 70 10 40 65 85 5 15 30 50 80 90 02-02-2023 133
  • 134. Department of Computer Science and Engineering 134 DELETION AVL_DELETE(T, n) p = n while p != NULL p->height = 1 + MAX(HEIGHT(p->left), HEIGHT(p->right)) if(BALANCE_FACTOR(p) <= -2 || balance_factor(p) >= 2) x = p if x->left->height > x->right->height y = x->left else y = x->right 02-02-2023
  • 135. Department of Computer Science and Engineering 135 DELETION if y->left->height > y->right->height z = y->left else if y->left->height < y->right->height z = y->right else if y == x->left z = y->left else z = y->right if y == x->left if z == x->left->left //case1 RIGHT_ROTATE(T, x) 02-02-2023
  • 136. Department of Computer Science and Engineering 136 DELETION else if z == x->left->right //case 3 LEFT_ROTATE(T, y) RIGHT_ROTATE(T, x) else if y == x->right if z == x->right->right //case 2 LEFT_ROTATET(T, x) else if z == x->right->left //case 4 RIGHT_ROTATE(T, y) LEFT_ROTATE(T, x) p = p->parent 02-02-2023
  • 137. Department of Computer Science and Engineering 137 ANALYSIS 02-02-2023
  • 138. Department of Computer Science and Engineering 138 ADVANTAGES & DISADVANTAGES ADVANTAGES • self sorting binary trees • It is highly efficient when there is a large number of input data which involves a lot of insertions. DISADVANTAGES • The code for AVL tree is much more complex than the code for BST and we have to handle a lot of corner cases. • Deletion operations cost high in AVL trees as they involve a lot of pointer changes and rotations. • Increase the pointer overhead which even tends to some negligiable extra space for very big inputs. 02-02-2023
  • 139. Department of Computer Science and Engineering 139 APPLICATIONS • Particularly used for look up intensive applications for example it is used for indexing large records in database to improve search • Used for all sorts of in-memory collections such as sets and dictionaries. • Used in Memory management subsystem of linux kernel to search memory regions of processes during preemption. 02-02-2023
  • 140. Department of Computer Science and Engineering 140 APPLICATIONS 02-02-2023
  • 141. Thank You Department of Computer Science and Engineering