SlideShare a Scribd company logo
UNIT II : TREES
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Data Structures and Algorithm Analysis in C by Mark Allen Weiss & Sumitabha Das, “Computer Fundamentals and C
Programming”, 1st Edition, McGraw Hill, 2018.
20CST32 – Data Structures
Syllabus – Unit Wise
4/6/2022 2.1 _ Trees Preliminaries 2
List of Exercises
4/6/2022 2.1 _ Trees Preliminaries 3
Text Book and Reference Book
4/6/2022 2.1 _ Trees Preliminaries 4
Unit II : Contents
1. Implementation of trees
2. Tree Traversals with an Application
3. Binary trees: Implementation
4. Expression trees
5. The Search Tree ADT: Binary Search Trees
– Construction
– Searching
– Insertion
– Deletion
– Find Min
– Find Max
6. AVL trees
– Rotation
– Insertion
– Deletion.
4/6/2022 5
2.1 _ Trees Preliminaries
Introduction
• For large amounts of input, the linear access time
of linked lists is prohibitive.
• In this unit we look at a simple data structure for
which the running time of most operations is
O(log n) on average.
• We also sketch a conceptually simple
modification to this data structure that
guarantees the above time bound in the worst
case and discuss a second modification that
essentially gives an O(log n) running time per
operation for a long sequence of instructions.
4/6/2022 2.1 _ Trees Preliminaries 6
Tree Representation
• Tree represents the nodes connected by edges. We will
discuss binary tree or binary search tree specifically.
• Binary Tree is a special data structure used for data
storage purposes.
• A binary tree has a special condition that each node
can have a maximum of two children.
• A binary tree has the benefits of both an ordered array
and a linked list as search is as quick as in a sorted
array and insertion or deletion operation are as fast as
in linked list.
4/6/2022 2.1 _ Trees Preliminaries 7
Trees
• The data structure that we are referring to is
known as a binary search tree.
• Trees in general are very useful abstractions in
computer science.
• Advantages:
– trees are used to implement the file system of several
popular operating systems.
– trees can be used to evaluate arithmetic expressions.
– trees to support searching operations in O(log n)
average time.
4/6/2022 2.1 _ Trees Preliminaries 8
Trees
• A tree can be defined in several ways.
• One natural way to define a tree is recursively.
• A tree is a collection of nodes.
• The collection can be empty, which is sometimes denoted as A.
• Otherwise, a tree consists of a distinguished node r, called the root, and
zero or more (sub)trees T1, T2, . . . , Tk, each of whose roots are
connected by a directed edge to r.
• The root of each subtree is said to be a child of r, and r is the parent of
each subtree root.
• From the recursive definition, we find that a tree is a collection of n nodes,
• one of which is the root, and n - 1 edges
4/6/2022 2.1 _ Trees Preliminaries 9
Tree Terms
• In the tree of Figure below, the root is A.
• Node F has A as a parent and K, L, and M as children.
• Each node may have an arbitrary number of children, possibly zero.
• Nodes with no children are known as leaves; the leaves in the tree below are B, C,
H, I, P, Q, K, L, M, and N.
• Nodes with the same parent are siblings; thus K, L, and M are all siblings.
• Grandparent and grandchild relations can be defined in a similar manner.
• A path from node n1 to nk is defined as a sequence of nodes n1, n2, . . . , nk.
• The length of this path is the number of edges on the path, namely k -1. There is a
path of length zero from every node to itself.
• Notice that in a tree there is exactly one path from the root to each node.
4/6/2022 2.1 _ Trees Preliminaries 10
Tree Terms
• For any node ni, the depth of ni is the length of the unique
path from the root to ni. Thus, the root is at depth 0.
• The height of ni is the longest path from ni to a leaf. Thus
all leaves are at height 0.
• The height of a tree is equal to the height of the root.
• For the tree in previous Figure,
– E is at depth 1 and height 2;
– F is at depth 1 and height 1;
– the height of the tree is 3.
• The depth of a tree is equal to the depth of the deepest
leaf; this is always equal to the height of the tree.
• If there is a path from n1 to n2, then n1 is an ancestor of
n2 and n2 is a descendant of n1. If n1=n2, then n1 is a
proper ancestor of n2 and n2 is a proper descendant of n1.
4/6/2022 2.1 _ Trees Preliminaries 11
Tree Representation
4/6/2022 2.1 _ Trees Preliminaries 12
Tree Terms
• Path − Path refers to the sequence of nodes along the edges of a tree.
• Root − The node at the top of the tree is called root. There is only one root
per tree and one path from the root node to any node.
• Parent − Any node except the root node has one edge upward to a node
called parent.
• Child − The node below a given node connected by its edge downward is
called its child node.
• Leaf − The node which does not have any child node is called the leaf
node.
• Subtree − Subtree represents the descendants of a node.
• Visiting − Visiting refers to checking the value of a node when control is on
the node.
• Traversing − Traversing means passing through nodes in a specific order.
• Levels − Level of a node represents the generation of a node. If the root
node is at level 0, then its next child node is at level 1, its grandchild is at
level 2, and so on.
• keys − Key represents a value of a node based on which a search operation
is to be carried out for a node.
4/6/2022 2.1 _ Trees Preliminaries 13
Thank you
4/6/2022 2.1 _ Trees Preliminaries 14
UNIT II : TREES
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Data Structures and Algorithm Analysis in C by Mark Allen Weiss & Sumitabha Das, “Computer Fundamentals and C
Programming”, 1st Edition, McGraw Hill, 2018.
20CST32 – Data Structures
Unit II : Contents
1. Implementation of trees
2. Tree Traversals with an Application
3. Binary trees: Implementation
4. Expression trees
5. The Search Tree ADT: Binary Search Trees
– Construction
– Searching
– Insertion
– Deletion
– Find Min
– Find Max
6. AVL trees
– Rotation
– Insertion
– Deletion.
4/6/2022 16
2.2 _ Tree Traversals
Tree Traversal
• Traversal is a process to visit all the nodes of a tree
and may print their values too.
• Because, all nodes are connected via edges (links) we
always start from the root (head) node.
• That is, we cannot randomly access a node in a tree.
• There are three ways which we use to traverse a tree −
– In-order Traversal
– Pre-order Traversal
– Post-order Traversal
• Generally, we traverse a tree to search or locate a
given item or key in the tree or to print all the values it
contains.
4/6/2022 2.2 _ Tree Traversals 17
In-order Traversal
• In this traversal method,
– the left subtree is visited first,
– then the root and
– later the right sub-tree.
• We should always remember that every node
may represent a subtree itself.
• If a binary tree is traversed in-order, the
output will produce sorted key values in an
ascending order.
4/6/2022 2.2 _ Tree Traversals 18
In-order Traversal
4/6/2022 2.2 _ Tree Traversals 19
• We start from A, and
following in-order traversal, we
move to its left subtree B.
• B is also traversed in-order.
• The process goes on until all
the nodes are visited.
•The output of inorder
traversal of this tree will be −
D → B → E → A → F → C → G
In-order Traversal – Algorithm & Code
• Until all nodes are traversed
• Step 1 − Recursively traverse left subtree.
• Step 2 − Visit root node.
• Step 3 − Recursively traverse right subtree.
4/6/2022 2.2 _ Tree Traversals 20
void inorder_traversal(struct node* root)
{
if(root != NULL)
{
inorder_traversal(root->leftChild);
printf("%d ",root->data);
inorder_traversal(root->rightChild);
}
}
Pre-order Traversal
• In this traversal method,
– the root node is visited first,
– then the left subtree and
– finally the right subtree.
4/6/2022 2.2 _ Tree Traversals 21
Pre-order Traversal
4/6/2022 2.2 _ Tree Traversals 22
• We start from A, and following
pre-order traversal, we first visit
A itself and then move to its left
subtree B.
• B is also traversed pre-order.
• The process goes on until all
the nodes are visited.
•The output of pre-order
traversal of this tree will be −
A → B → D → E → C → F → G
Pre-order Traversal – Algorithm & Code
• Until all nodes are traversed
• Step 1 − Visit root node.
• Step 2 − Recursively traverse left subtree.
• Step 3 − Recursively traverse right subtree.
4/6/2022 2.2 _ Tree Traversals 23
void preorder_traversal(struct node* root)
{
if(root != NULL)
{
printf("%d ",root->data);
preorder_traversal(root->leftChild);
preorder_traversal(root->rightChild);
}
}
Post-order Traversal
• In this traversal method, the root node is
visited last, hence the name.
– First we traverse the left subtree,
– then the right subtree and
– finally the root node.
4/6/2022 2.2 _ Tree Traversals 24
Post-order Traversal
4/6/2022 2.2 _ Tree Traversals 25
•We start from A, and following
Post-order traversal, we first
visit the left subtree B.
•B is also traversed post-order.
•The process goes on until all
the nodes are visited.
•The output of post-order
traversal of this tree will be −
D → E → B → F → G → C → A
Post-order Traversal – Algorithm & Code
• Until all nodes are traversed
• Step 1 − Recursively traverse left subtree.
• Step 2 − Recursively traverse right subtree.
• Step 3 − Visit root node.
4/6/2022 2.2 _ Tree Traversals 26
void postorder_traversal(struct node* root)
{
if(root != NULL)
{
postorder_traversal(root->leftChild);
postorder_traversal(root->rightChild);
printf("%d ",root->data);
}
}
Program to Implement Tree Traversal
4/6/2022 2.2 _ Tree Traversals 27
4/6/2022 2.2 _ Tree Traversals 28
4/6/2022 2.2 _ Tree Traversals 29
4/6/2022 2.2 _ Tree Traversals 30
4/6/2022 2.2 _ Tree Traversals 31
4/6/2022 2.2 _ Tree Traversals 32
4/6/2022 2.2 _ Tree Traversals 33
4/6/2022 2.2 _ Tree Traversals 34
Thank you
4/6/2022 2.2 _ Tree Traversals 35
UNIT II : TREES
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Data Structures and Algorithm Analysis in C by Mark Allen Weiss & Sumitabha Das, “Computer Fundamentals and C
Programming”, 1st Edition, McGraw Hill, 2018.
20CST32 – Data Structures
Unit II : Contents
1. Implementation of trees
2. Tree Traversals with an Application
3. Binary trees: Implementation
4. Expression trees
5. The Search Tree ADT: Binary Search Trees
– Construction
– Searching
– Insertion
– Deletion
– Find Min
– Find Max
6. AVL trees
– Rotation
– Insertion
– Deletion.
4/6/2022 37
2.3 _ Binary Tree
Binary Vs Binary Search Tree
4/6/2022 2.3 _ Binary Tree 38
Binary Tree
• A tree whose elements have at most 2 children is
called a binary tree.
• Since each element in a binary tree can have only
2 children, we typically name them the left and
right child.
4/6/2022 2.3 _ Binary Tree 39
Binary Tree - Examples
4/6/2022 2.3 _ Binary Tree 40
Binary Search Tree
• Binary Search Tree is a node-based
binary tree data structure which
has the following properties:
– 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.
– There must be no duplicate nodes.
4/6/2022 2.3 _ Binary Tree 41
Binary Tree Vs Binary Search Tree
4/6/2022 2.3 _ Binary Tree 42
Types of Binary Tree
• Full/Proper/Strict Binary Tree
• Complete Binary Tree
• Perfect Binary Tree
• Degenerate / Pathological Binary Tree
– Left Skewed
– Right Skewed
– Pathological
• Balanced Binary Tree
4/6/2022 2.3 _ Binary Tree 43
Full/Proper/Strict Binary Tree
• The full binary tree is also known as a strict
binary tree.
• The tree can only be considered as the full
binary tree if each node must contain either 0
or 2 children.
• OR
• The full binary tree can also be defined as the
tree in which each node must contain 2
children except the leaf nodes.
4/6/2022 2.3 _ Binary Tree 44
Example- Full/Proper/Strict Binary Tree
4/6/2022 2.3 _ Binary Tree 45
Full Binary Tree - Example
4/6/2022 2.3 _ Binary Tree 46
Complete Binary Tree
• The complete binary tree is a tree in which all
the nodes are completely filled except the last
level.
• In the last level, all the nodes must be as left
as possible.
• In a complete binary tree, the nodes should be
added from the left.
• Let's create a complete binary tree.
4/6/2022 2.3 _ Binary Tree 47
Example – Complete Binary Tree
4/6/2022 2.3 _ Binary Tree 48
Complete Binary Tree - Example
4/6/2022 2.3 _ Binary Tree 49
Perfect Binary Tree
• A tree is a perfect binary tree if all the internal
nodes have 2 children, and all the leaf nodes
are at the same level.
4/6/2022 2.3 _ Binary Tree 50
Perfect Binary Tree - Example
4/6/2022 2.3 _ Binary Tree 51
Note:
4/6/2022 2.3 _ Binary Tree 52
Degenerate Binary Tree
• The degenerate binary tree is a tree in which
all the internal nodes have only one children.
4/6/2022 2.3 _ Binary Tree 53
left-skewed tree
right-skewed tree
Degenerate Binary Tree - Example
4/6/2022 2.3 _ Binary Tree 54
Balanced binary Tree
• The balanced binary tree is a tree in which both
the left and right trees differ by atmost 1.
• For example, AVL and Red-Black trees are
balanced binary tree.
4/6/2022 2.3 _ Binary Tree 55
This tree is a balanced binary tree because the
difference between the left subtree and right
subtree is zero.
Balanced Binary Tree - Example
4/6/2022 2.3 _ Binary Tree 56
The above tree is not a balanced binary tree because the difference
between the left subtree and the right subtree is greater than 1.
To Find Height and Min/Max Nodes in Binary Tree
• Depth of Node x: Length of path from root to Node x
• Height of Node x: Number of edges in the longest path from node x
to leaf node
• Height of tree: Height of the tree is the height of the root
• Level of node: Set of all nodes at a given depth is called the level of
the tree
• Trees with N nodes will have N-1 edges
• Depth of root node is Zero
• Root node is at level Zero
• Height of leaf node is Zero
• Height of tree with one node is Zero
• An empty tree is also a valid binary tree
• Every node except root is connected by a directed edge from
exactly one node to other node and direction is: parent -> children
4/6/2022 2.3 _ Binary Tree 57
Example
4/6/2022 2.3 _ Binary Tree 58
Maximum and Minimum Number of Nodes of
binary tree
• Maximum number of nodes of binary tree of height
“h” is 2h+1 - 1.
4/6/2022 2.3 _ Binary Tree 59
• Minimum number of nodes of binary tree of
height “h” is “h+1”
4/6/2022 2.3 _ Binary Tree 60
Height of the binary tree with maximum and
minimum nodes of binary tree
4/6/2022 2.3 _ Binary Tree 61
• Minimum height of the binary tree of with maximum number of
nodes as “n”
• For any binary tree of height “h”, maximum number of nodes =
2h+1 – 1
Here, Max nodes = n
So, n = 2h+1 – 1
• => n + 1 = 2h+1
• Applying log on both sides,
• =>log(n+1) = log2h+1
• => log(n+1) = (h+1) log2
• =>log(n+1)=(h+1)
• =>Height of the binary with maximum “n” nodes =>
• h = ⌈ log(n+1) ⌉ - 1
• Minimum height of the binary tree of with
maximum number of nodes as “n”
• For any binary tree of height “h”, minimum
number of nodes = h + 1
• =>n=h+1
• =>Height of the binary with minimum “n”
nodes => h = n-1
4/6/2022 2.3 _ Binary Tree 62
4/6/2022 2.3 _ Binary Tree 63
Binary Tree Implementation - Program
4/6/2022 2.3 _ Binary Tree 64
4/6/2022 2.3 _ Binary Tree 65
4/6/2022 2.3 _ Binary Tree 66
Thank you
4/6/2022 2.3 _ Binary Tree 67
UNIT II : TREES
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Data Structures and Algorithm Analysis in C by Mark Allen Weiss & Sumitabha Das, “Computer Fundamentals and C
Programming”, 1st Edition, McGraw Hill, 2018.
20CST32 – Data Structures
Unit II : Contents
1. Implementation of trees
2. Tree Traversals with an Application
3. Binary trees: Implementation
4. Expression trees
5. The Search Tree ADT: Binary Search Trees
– Construction
– Searching
– Insertion
– Deletion
– Find Min
– Find Max
6. AVL trees
– Rotation
– Insertion
– Deletion.
4/6/2022 69
2.4 _ Expression Tree
Expression Tree
• The expression tree is a binary tree in which
each
– internal node corresponds to the operator and
– each leaf node corresponds to the operand.
4/6/2022 2.4 _ Expression Tree 70
Expression Tree - Example
• expression tree for 3 + ((5+9)*2) would be:
4/6/2022 2.4 _ Expression Tree 71
Constructing an Expression Tree
• First, convert infix to postfix.
• Next, We read our expression one symbol at a
time.
– If the symbol is an operand, we create a one node
tree and push a pointer to it onto a stack.
– If the symbol is an operator, we pop pointers to two
trees T1 and T2 from the stack (T1 is popped first) and
form a new tree whose root is the operator and
whose left and right children point to T2 and T1
respectively. A pointer to this new tree is then pushed
onto the stack.
4/6/2022 2.4 _ Expression Tree 72
Example
• (a+b)*(c*(d+e))
• First, Convert Infix into postfix.
– a b + c d e + * *
4/6/2022 2.4 _ Expression Tree 73
Example (cntd.,)
• The first two symbols are operands, so we
create one-node trees and push pointers to
them onto a stack.*
4/6/2022 2.4 _ Expression Tree 74
a b + c d e + * *
Example (cntd.,)
• Next, a '+' is read, so two pointers to trees are
popped, a new tree is formed, and a pointer
to it is pushed onto the stack.*
4/6/2022 2.4 _ Expression Tree 75
a b + c d e + * *
Example (cntd.,)
• Next, c, d, and e are read, and for each a one-
node tree is created and a pointer to the
corresponding tree is pushed onto the stack.
4/6/2022 2.4 _ Expression Tree 76
a b + c d e + * *
Example (cntd.,)
• Now a '+' is read, so two trees are merged.
4/6/2022 2.4 _ Expression Tree 77
a b + c d e + * *
Example (cntd.,)
• Continuing, a '*' is read, so we pop two tree
pointers and form a new tree with a '*' as
root.
4/6/2022 2.4 _ Expression Tree 78
a b + c d e + * *
Example (cntd.,)
• Finally, the last symbol is read, two trees are
merged, and a pointer to the final tree is left
on the stack.
4/6/2022 2.4 _ Expression Tree 79
a b + c d e + * *
Thank you
4/6/2022 2.4 _ Expression Tree 80
UNIT II : TREES
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Data Structures and Algorithm Analysis in C by Mark Allen Weiss & Sumitabha Das, “Computer Fundamentals and C
Programming”, 1st Edition, McGraw Hill, 2018.
20CST32 – Data Structures
Unit II : Contents
1. Implementation of trees
2. Tree Traversals with an Application
3. Binary trees: Implementation
4. Expression trees
5. The Search Tree ADT :Binary Search Trees
– Construction
– Searching
– Find Min
– Find Max
– Insertion
– Deletion
6. AVL trees
– Rotation
– Insertion
– Deletion.
4/6/2022 82
2.5 _ Binary Search Tree
Search Tree ADT
• Search Tree ADT contains the following
operations:
– Construction
– Searching
– Insertion
– Deletion
– Find Min
– Find Max
4/6/2022 2.5 _ Binary Search Tree 83
Binary Search Tree
• Binary Search tree exhibits a special behavior.
• A node's
– left child must have a value less than its parent's
value and
– right child must have a value greater than its
parent value
– The left and right subtree each must also be a
binary search tree.
– There must be no duplicate nodes.
4/6/2022 2.5 _ Binary Search Tree 84
Binary Search Tree
4/6/2022 2.5 _ Binary Search Tree 85
Tree Node
• The code to write a tree node would be
similar to what is given below.
• It has a data part and references to its left and
right child nodes.
4/6/2022 2.5 _ Binary Search Tree 86
BST Basic Operations
• The basic operations that can be performed on a
binary search tree data structure, are the
following −
– Insert − Inserts an element in a tree/create a tree.
– Search − Searches an element in a tree.
– Preorder Traversal − Traverses a tree in a pre-order
manner.
– Inorder Traversal − Traverses a tree in an in-order
manner.
– Postorder Traversal − Traverses a tree in a post-order
manner.
4/6/2022 2.5 _ Binary Search Tree 87
Insertion Operation - BST
• The very first insertion creates the tree.
• Afterwards, whenever an element is to be
inserted, first locate its proper location.
• Start searching from the root node,
– then if the data is less than the key value,
– search for the empty location in the left subtree and
– insert the data.
• Otherwise,
– search for the empty location in the right subtree and
– insert the data.
4/6/2022 2.5 _ Binary Search Tree 88
Insertion on BST - Algorithm
4/6/2022 2.5 _ Binary Search Tree 89
Implementation – BST Insertion
4/6/2022 2.5 _ Binary Search Tree 90
Implementation – BST Insertion
4/6/2022 2.5 _ Binary Search Tree 91
Implementation – BST Insertion
4/6/2022 2.5 _ Binary Search Tree 92
Search Operation - BST
• Whenever an element is to be searched,
– start searching from the root node,
– then if the data is less than the key value,
– search for the element in the left subtree.
• Otherwise,
– search for the element in the right subtree.
• Follow the same algorithm for each node.
4/6/2022 2.5 _ Binary Search Tree 93
Algorithm – Search on BST
4/6/2022 2.5 _ Binary Search Tree 94
Implementation – Search on BST
4/6/2022 2.5 _ Binary Search Tree 95
Find an element in BST
• This operation requires returning a pointer to the node
in tree T that has key X or NULL if there is no such
node.
• The find operation as follows.
– Check whether the root is NULL if so then return NULL.
– Otherwise, check the value X with the root node value (ie.
T->Element)
– If X is equal to T->Element, return T
– If X is less than T->Element, traverse the left of T
recursively.
– If X is greater than T->Element, traverse the right of T
recursively.
4/6/2022 2.5 _ Binary Search Tree 96
Find
• Position Find( ElementType 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;
• }
4/6/2022 2.5 _ Binary Search Tree 97
Example
• To find an element 4 (X = 4) in the below tree
– In the first fig, the element 4 is checked with root 6. 4 is
less than 6. So goto the left subtree.
– In the second fig, element 4 is checked with node 2. 4 is
greater than 2. So goto the right subtree.
– In the third fig, the element 4 is checked with node 4. The
element is equal. So return 4.
4/6/2022 2.5 _ Binary Search Tree 98
Find Min
• This operation returns the position of the
smallest element in the tree.
• To find the minimum element, start at the
root and go left as long as there is a left child.
• The stopping point is the smallest element.
4/6/2022 2.5 _ Binary Search Tree 99
Recursive / Non-recursive routine for
Find Min
4/6/2022 2.5 _ Binary Search Tree 100
Find Max
• This operation returns the position of the
largest element in the tree.
• To find the maximum element, start at the
root and go right as long as there is a right
child.
• The stopping point is the largest element.
4/6/2022 2.5 _ Binary Search Tree 101
Recursive / Non-recursive routine for
Find Max
4/6/2022 2.5 _ Binary Search Tree 102
Insert
• To insert the element X in to the tree, check with
the root node T.
• If it is less than the root, traverse the left sub
tree recursively until it reaches the T->Left equals
to NULL. Then X is placed in T->Left.
• If it is greater than the root, traverse the right
sub tree recursively until it reaches the T->Right
equals to NULL. Then X is placed in T->Right.
• If X is found in the tree, do nothing.
4/6/2022 2.5 _ Binary Search Tree 103
Insert
• SearchTree Insert( ElementType X, SearchTree T )
• {
• if( T = = NULL )
• { /* Create and return a one-node tree */
• T = malloc ( sizeof (struct TreeNode) );
• if( T != NULL )
• {
• T-Element = X;
• T->Left = 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 );
• /* else X is in the tree already. We'll do nothing */
• return T;
• }
• }
4/6/2022 2.5 _ Binary Search Tree 104
Example - To insert 8, 4, 1, 6, 5, 7, 10
• First insert element 8 which is considered as
root.
• Next insert element 4, 4 is less than 8, traverse
towards left.
4/6/2022 2.5 _ Binary Search Tree 105
Example - To insert 8, 4, 1, 6, 5, 7, 10
• Next insert element 1, 1<8 traverse towards left. 1<4 traverse
towards left.
• To insert element 6, 6<8 traverse towards left. 6>4, place it as right
child of 4.
• To insert element 5, 5<8 traverse towards left. 5>4, traverse
towards right. 5<6, place it as left child of 6.
4/6/2022 2.5 _ Binary Search Tree 106
Example - To insert 8, 4, 1, 6, 5, 7, 10
• To insert element 7, 7<8 traverse towards left. 7>4,
traverse towards right. 7>6, place it as right child of 6.
• To insert element 10, 10>8, place it as a right child of 8.
4/6/2022 2.5 _ Binary Search Tree 107
Delete
• While deleting a node from a tree, the
memory is to be released.
• Deletion operation is the complex operation
in the binary search tree.
• To delete a node from the tree consider the
following three possibilities.
– Case 1: Node to be deleted is a leaf node
– Case 2: Node with one child.
– Case 3: Node with two children.
4/6/2022 2.5 _ Binary Search Tree 108
Case 1: Deleting the leaf node
1. Search the parent of the leaf node.
2. Make the parent link of the leaf node as NULL.
3. Release Memory.
4/6/2022 2.5 _ Binary Search Tree 109
Example: Deletion of node 6
Case 2: Deleting the node with only one child.
4/6/2022 2.5 _ Binary Search Tree 110
1. Search the parent of the node to be deleted.
2. Assign the parent link to the child node of the node to be deleted.
3. Release the memory of the deleted node.
4. If a node has one child, it can be deleted by adjusting its parent
pointer to point to its child node.
Eg. Deletion of a node (4) with one child, before and after
Case 3: Deleting a node with two children.
4/6/2022 2.5 _ Binary Search Tree 111
• Inorder to delete a node with two children, it can be replaced by a
node whose key is larger than any node in P‟s right sub tree to
preserve the Binary Search Tree property.
• The possible nodes that could replace node P are
– Rule 1: The node with the largest value in P‟s left sub tree.
– Rule 2: The node with the smallest value in P‟s right sub tree.
Eg: Deletion of a node 4 with two children, before and after
Delete
4/6/2022 2.5 _ Binary Search Tree 112
• SearchTree Delete( ElementType X, SearchTree T )
• {
• Position TmpCell;
• if( T = = NULL )
• Error("Element not found"); else
• if( X < T->Element ) /* Go left */
• T->Left = Delete( X, T->Left );
• else
• if( X > T->Element ) /* Go right */
• T->Right = Delete( X, T->Right );
• else /* Found element to be deleted */
• if( T->Left && T->Right ) /* Two children */
• { /* Replace with smallest in right subtree */
• TmpCell = FindMin( T->Right );
• T->Element = TmpCell->Element;
• T->Right = Delete( T->Element, T->Right );
• }
• else /* One or zero child */
• {
• TmpCell = T;
• if( T->Left = = NULL ) /* Only a right child */
• T = T->Right;
• if( T->Right = = NULL ) /* Only a left child */
• T = T->Left;
• free(TmpCell );
• }
• return T;
• }
BST
• How many distinct binary search trees can be
created out of 3 distinct keys?
4/6/2022 2.5 _ Binary Search Tree 113
Thank you
4/6/2022 2.5 _ Binary Search Tree 114
UNIT II : TREES
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Data Structures and Algorithm Analysis in C by Mark Allen Weiss & Sumitabha Das, “Computer Fundamentals and C
Programming”, 1st Edition, McGraw Hill, 2018.
20CST32 – Data Structures
Unit II : Contents
1. Implementation of trees
2. Tree Traversals with an Application
3. Binary trees: Implementation
4. Expression trees
5. The Search Tree ADT :Binary Search Trees
– Construction
– Searching
– Find Min
– Find Max
– Insertion
– Deletion
6. AVL trees
– Rotation
– Insertion
– Deletion
4/6/2022 116
2.6 _ AVL Trees
AVL Tree
• AVL Tree is invented by GM Adelson - Velsky and EM Landis
in 1962. The tree is named AVL in honour of its inventors.
• An AVL (Adelson-Velskii and Landis) tree is a binary search
tree with a balance condition.
• AVL Tree can be defined as height balanced binary search
tree in which each node is associated with a balance factor
which is calculated by subtracting the height of its right
sub-tree from that of its left sub-tree.
• The balance condition must be easy to maintain, and it
ensures that the depth of the tree is O(log n).
• The simplest idea is to require that the left and right
subtrees have the same height.
4/6/2022 2.6 _ AVL Trees 117
Balancing Factor
• Balancing factor is -1,0,1
• If balance factor of any node is 1, it means that the left
sub-tree is one level higher than the right sub-tree.
• If balance factor of any node is 0, it means that the left
sub-tree and right sub-tree contain equal height.
• If balance factor of any node is -1, it means that the left
sub-tree is one level lower than the right sub-tree.
4/6/2022 2.6 _ AVL Trees 118
Example – AVL Tree
4/6/2022 2.6 _ AVL Trees 119
Why AVL Tree?
• AVL tree controls the height of the binary
search tree by not letting it to be skewed.
• The time taken for all operations in a binary
search tree of height h is O(h).
• However, it can be extended to O(n) if the BST
becomes skewed (i.e. worst case).
• By limiting this height to log n, AVL tree
imposes an upper bound on each operation to
be O(log n) where n is the number of nodes.
4/6/2022 2.6 _ AVL Trees 120
Time Complexity
4/6/2022 2.6 _ AVL Trees 121
Operations on AVL tree
• Due to the fact that, AVL tree is also a binary
search tree therefore, all the operations are
performed in the same way as they are
performed in a binary search tree.
– Searching and traversing do not lead to the
violation in property of AVL tree.
– However, insertion and deletion are the
operations which can violate this property and
therefore, they need to be revisited.
4/6/2022 2.6 _ AVL Trees 122
AVL Tree - Rotations
4/6/2022 2.6 _ AVL Trees 123
AVL Tree - Rotations
• If the balance factor of any node in an AVL tree becomes less than -1 or greater
than 1, the tree has to be balanced by making a simple modifications in the tree
called rotation.
• An AVL tree causes imbalance, when any one of the following conditions occur. α –
is the node must be rebalanced.
– Case 1: An insertion from the left sub tree of the left child of node α. [LL
Rotation]
– Case 2: An insertion into the right sub tree of the left child of α. [LR Rotation]
– Case 3: An insertion into the left sub tree of the right child of α. [RL Rotation]
– Case 4: An insertion into the right sub tree of the right child of α. [RR
Rotation]
• These imbalances can be overcome by
– Single Rotation
– Double Rotation
• Case 1 and Case 4 imbalance (left – left or right – right) is fixed by a single rotation
of the tree.
• Case 2 and Case 3 imbalance (left – right or right – left) is fixed by double rotation.
4/6/2022 2.6 _ AVL Trees 124
LL Rotation
• When BST becomes unbalanced, due to a node is
inserted into the left subtree of the left subtree of C,
then we perform LL rotation.
• LL rotation is clockwise rotation, which is applied on
the edge below a node having balance factor 2.
4/6/2022 2.6 _ AVL Trees 125
RR Rotation
• When BST becomes unbalanced, due to a node is inserted
into the right subtree of the right subtree of A, then we
perform RR rotation.
• RR rotation is an anticlockwise rotation, which is applied on
the edge below a node having balance factor -2.
4/6/2022 2.6 _ AVL Trees 126
LR Rotation
• Double rotations are bit tougher than single
rotation which has already explained above.
• LR rotation = RR rotation + LL rotation
• i.e., first RR rotation is performed on subtree
and then LL rotation is performed on full tree,
• Here the full tree we mean the first node from
the path of inserted node whose balance
factor is other than -1, 0, or 1.
4/6/2022 2.6 _ AVL Trees 127
LR Rotation
4/6/2022 2.6 _ AVL Trees 128
RL Rotation
4/6/2022 2.6 _ AVL Trees 129
• As already discussed, that double rotations are
bit tougher than single rotation which has already
explained above.
• R L rotation = LL rotation + RR rotation
• i.e., first LL rotation is performed on subtree and
then RR rotation is performed on full tree,
• Here the full tree we mean the first node from
the path of inserted node whose balance factor is
other than -1, 0, or 1.
RL Rotation
4/6/2022 2.6 _ AVL Trees 130
AVL Tree - Insertion
• In an AVL tree, the insertion operation is performed
with O(log n) time complexity.
• In AVL Tree, a new node is always inserted as a leaf
node.
• The insertion operation is performed as follows...
– Step 1 - Insert the new element into the tree using Binary
Search Tree insertion logic.
– Step 2 - After insertion, check the Balance Factor of every
node.
– Step 3 - If the Balance Factor of every node is 0 or 1 or -
1 then go for next operation.
– Step 4 - If the Balance Factor of any node is other than 0
or 1 or -1 then that tree is said to be imbalanced. In this
case, perform suitable Rotation to make it balanced and
go for next operation.
4/6/2022 2.6 _ AVL Trees 131
AVL Tree Example – 51,26,11,6,8,4,31
4/6/2022 2.6 _ AVL Trees 132
AVL Tree - Deletion
• The deletion operation in AVL Tree is similar
to deletion operation in BST.
• But after every deletion operation, we need
to check with the Balance Factor condition.
• If the tree is balanced after deletion go for
next operation otherwise perform suitable
rotation to make the tree Balanced.
4/6/2022 2.6 _ AVL Trees 133
4/6/2022 2.6 _ AVL Trees 134
4/6/2022 2.6 _ AVL Trees 135
4/6/2022 2.6 _ AVL Trees 136
4/6/2022 2.6 _ AVL Trees 137
4/6/2022 2.6 _ AVL Trees 138
4/6/2022 2.6 _ AVL Trees 139
4/6/2022 2.6 _ AVL Trees 140
Thank you
4/6/2022 2.6 _ AVL Trees 141

More Related Content

What's hot

Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures
Gurukul Kangri Vishwavidyalaya - Faculty of Engineering and Technology
 
Threaded Binary Tree.pptx
Threaded Binary Tree.pptxThreaded Binary Tree.pptx
Threaded Binary Tree.pptx
pavankumarjakkepalli
 
B trees in Data Structure
B trees in Data StructureB trees in Data Structure
B trees in Data StructureAnuj Modi
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.ppt
SeethaDinesh
 
Lec 17 heap data structure
Lec 17 heap data structureLec 17 heap data structure
Lec 17 heap data structureSajid Marwat
 
Singly link list
Singly link listSingly link list
Singly link list
Rojin Khadka
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
Lemia Algmri
 
Searching, Sorting and Hashing Techniques
Searching, Sorting and Hashing TechniquesSearching, Sorting and Hashing Techniques
Searching, Sorting and Hashing Techniques
Selvaraj Seerangan
 
Trees
TreesTrees
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
sagar yadav
 
linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structures
DurgaDeviCbit
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
Syed Zaid Irshad
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
anooppjoseph
 
Frequent Pattern growth algorithm
Frequent Pattern growth algorithmFrequent Pattern growth algorithm
Frequent Pattern growth algorithm
Ashis Kumar Chanda
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data Structure
Meghaj Mallick
 
linked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutoriallinked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutorial
Afzal Badshah
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
Abdullah Al-hazmy
 
Queue ppt
Queue pptQueue ppt
Queue ppt
SouravKumar328
 
Advanced Trees
Advanced TreesAdvanced Trees
Advanced Trees
Selvaraj Seerangan
 

What's hot (20)

Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures
 
Threaded Binary Tree.pptx
Threaded Binary Tree.pptxThreaded Binary Tree.pptx
Threaded Binary Tree.pptx
 
B trees in Data Structure
B trees in Data StructureB trees in Data Structure
B trees in Data Structure
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.ppt
 
Lec 17 heap data structure
Lec 17 heap data structureLec 17 heap data structure
Lec 17 heap data structure
 
Singly link list
Singly link listSingly link list
Singly link list
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
 
Searching, Sorting and Hashing Techniques
Searching, Sorting and Hashing TechniquesSearching, Sorting and Hashing Techniques
Searching, Sorting and Hashing Techniques
 
Trees
TreesTrees
Trees
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Heaps & priority queues
Heaps & priority queuesHeaps & priority queues
Heaps & priority queues
 
linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structures
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Frequent Pattern growth algorithm
Frequent Pattern growth algorithmFrequent Pattern growth algorithm
Frequent Pattern growth algorithm
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data Structure
 
linked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutoriallinked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutorial
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Queue ppt
Queue pptQueue ppt
Queue ppt
 
Advanced Trees
Advanced TreesAdvanced Trees
Advanced Trees
 

Similar to Trees

DSA IV Unit.pptx
DSA IV Unit.pptxDSA IV Unit.pptx
DSA IV Unit.pptx
AyeshaTakreem1
 
Data Structures 4
Data Structures 4Data Structures 4
Data Structures 4
Dr.Umadevi V
 
Tree
TreeTree
Tree
sbkbca
 
cppggggggggggggggggggggggggggggggggggggggg.pptx
cppggggggggggggggggggggggggggggggggggggggg.pptxcppggggggggggggggggggggggggggggggggggggggg.pptx
cppggggggggggggggggggggggggggggggggggggggg.pptx
ShruthiS594607
 
UNIT-4 TREES.ppt
UNIT-4 TREES.pptUNIT-4 TREES.ppt
UNIT-4 TREES.ppt
SIVAKUMARM603675
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
ER Punit Jain
 
Unit 4.1 (tree)
Unit 4.1 (tree)Unit 4.1 (tree)
Unit 4.1 (tree)
DurgaDeviCbit
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
worldchannel
 
Module - 5_Trees.pdf
Module - 5_Trees.pdfModule - 5_Trees.pdf
Module - 5_Trees.pdf
AnuradhaJadiya1
 
Tree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanTree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal Khan
Daniyal Khan
 
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
 
Unit 3 trees
Unit 3   treesUnit 3   trees
Unit 3 trees
LavanyaJ28
 
Introduction to tree ds
Introduction to tree dsIntroduction to tree ds
Introduction to tree ds
Viji B
 
Unit 3,4.docx
Unit 3,4.docxUnit 3,4.docx
Unit 3,4.docx
Revathiparamanathan
 
Mca iii dfs u-4 tree and graph
Mca iii dfs u-4 tree and graphMca iii dfs u-4 tree and graph
Mca iii dfs u-4 tree and graph
Rai University
 
Bca ii dfs u-3 tree and graph
Bca  ii dfs u-3 tree and graphBca  ii dfs u-3 tree and graph
Bca ii dfs u-3 tree and graph
Rai University
 
B tree ,B plus and graph
B tree ,B plus and graph B tree ,B plus and graph
B tree ,B plus and graph
RaaviKapoor
 
Data Structures 5
Data Structures 5Data Structures 5
Data Structures 5
Dr.Umadevi V
 
Unit II,III - Data Structures.pdf
Unit II,III - Data Structures.pdfUnit II,III - Data Structures.pdf
Unit II,III - Data Structures.pdf
KPRevathiAsstprofITD
 

Similar to Trees (20)

DSA IV Unit.pptx
DSA IV Unit.pptxDSA IV Unit.pptx
DSA IV Unit.pptx
 
Data Structures 4
Data Structures 4Data Structures 4
Data Structures 4
 
Tree
TreeTree
Tree
 
cppggggggggggggggggggggggggggggggggggggggg.pptx
cppggggggggggggggggggggggggggggggggggggggg.pptxcppggggggggggggggggggggggggggggggggggggggg.pptx
cppggggggggggggggggggggggggggggggggggggggg.pptx
 
UNIT-4 TREES.ppt
UNIT-4 TREES.pptUNIT-4 TREES.ppt
UNIT-4 TREES.ppt
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
 
Unit 4.1 (tree)
Unit 4.1 (tree)Unit 4.1 (tree)
Unit 4.1 (tree)
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
 
Module - 5_Trees.pdf
Module - 5_Trees.pdfModule - 5_Trees.pdf
Module - 5_Trees.pdf
 
Tree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanTree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal Khan
 
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 trees
Unit 3   treesUnit 3   trees
Unit 3 trees
 
Introduction to tree ds
Introduction to tree dsIntroduction to tree ds
Introduction to tree ds
 
Unit III.ppt
Unit III.pptUnit III.ppt
Unit III.ppt
 
Unit 3,4.docx
Unit 3,4.docxUnit 3,4.docx
Unit 3,4.docx
 
Mca iii dfs u-4 tree and graph
Mca iii dfs u-4 tree and graphMca iii dfs u-4 tree and graph
Mca iii dfs u-4 tree and graph
 
Bca ii dfs u-3 tree and graph
Bca  ii dfs u-3 tree and graphBca  ii dfs u-3 tree and graph
Bca ii dfs u-3 tree and graph
 
B tree ,B plus and graph
B tree ,B plus and graph B tree ,B plus and graph
B tree ,B plus and graph
 
Data Structures 5
Data Structures 5Data Structures 5
Data Structures 5
 
Unit II,III - Data Structures.pdf
Unit II,III - Data Structures.pdfUnit II,III - Data Structures.pdf
Unit II,III - Data Structures.pdf
 

More from Selvaraj Seerangan

Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Selvaraj Seerangan
 
Unit 5 _ Fog Computing .pdf
Unit 5 _ Fog Computing .pdfUnit 5 _ Fog Computing .pdf
Unit 5 _ Fog Computing .pdf
Selvaraj Seerangan
 
CAT III Answer Key.pdf
CAT III Answer Key.pdfCAT III Answer Key.pdf
CAT III Answer Key.pdf
Selvaraj Seerangan
 
END SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptxEND SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptx
Selvaraj Seerangan
 
Design Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptxDesign Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptx
Selvaraj Seerangan
 
CAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptxCAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptx
Selvaraj Seerangan
 
[PPT] _ Unit 5 _ Evolve.pptx
[PPT] _ Unit 5 _ Evolve.pptx[PPT] _ Unit 5 _ Evolve.pptx
[PPT] _ Unit 5 _ Evolve.pptx
Selvaraj Seerangan
 
[PPT] _ Unit 4 _ Engage.pptx
[PPT] _ Unit 4 _ Engage.pptx[PPT] _ Unit 4 _ Engage.pptx
[PPT] _ Unit 4 _ Engage.pptx
Selvaraj Seerangan
 
[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptx[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptx
Selvaraj Seerangan
 
CAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptxCAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptx
Selvaraj Seerangan
 
Design Thinking - Empathize Phase
Design Thinking - Empathize PhaseDesign Thinking - Empathize Phase
Design Thinking - Empathize Phase
Selvaraj Seerangan
 
CAT-II Answer Key.pdf
CAT-II Answer Key.pdfCAT-II Answer Key.pdf
CAT-II Answer Key.pdf
Selvaraj Seerangan
 
PSP LAB MANUAL.pdf
PSP LAB MANUAL.pdfPSP LAB MANUAL.pdf
PSP LAB MANUAL.pdf
Selvaraj Seerangan
 
18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdf18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdf
Selvaraj Seerangan
 
DS LAB MANUAL.pdf
DS LAB MANUAL.pdfDS LAB MANUAL.pdf
DS LAB MANUAL.pdf
Selvaraj Seerangan
 
CAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptxCAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptx
Selvaraj Seerangan
 
[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx
Selvaraj Seerangan
 
CAT-1 Answer Key.doc
CAT-1 Answer Key.docCAT-1 Answer Key.doc
CAT-1 Answer Key.doc
Selvaraj Seerangan
 
Unit 3 Complete.pptx
Unit 3 Complete.pptxUnit 3 Complete.pptx
Unit 3 Complete.pptx
Selvaraj Seerangan
 
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
Selvaraj Seerangan
 

More from Selvaraj Seerangan (20)

Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
 
Unit 5 _ Fog Computing .pdf
Unit 5 _ Fog Computing .pdfUnit 5 _ Fog Computing .pdf
Unit 5 _ Fog Computing .pdf
 
CAT III Answer Key.pdf
CAT III Answer Key.pdfCAT III Answer Key.pdf
CAT III Answer Key.pdf
 
END SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptxEND SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptx
 
Design Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptxDesign Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptx
 
CAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptxCAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptx
 
[PPT] _ Unit 5 _ Evolve.pptx
[PPT] _ Unit 5 _ Evolve.pptx[PPT] _ Unit 5 _ Evolve.pptx
[PPT] _ Unit 5 _ Evolve.pptx
 
[PPT] _ Unit 4 _ Engage.pptx
[PPT] _ Unit 4 _ Engage.pptx[PPT] _ Unit 4 _ Engage.pptx
[PPT] _ Unit 4 _ Engage.pptx
 
[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptx[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptx
 
CAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptxCAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptx
 
Design Thinking - Empathize Phase
Design Thinking - Empathize PhaseDesign Thinking - Empathize Phase
Design Thinking - Empathize Phase
 
CAT-II Answer Key.pdf
CAT-II Answer Key.pdfCAT-II Answer Key.pdf
CAT-II Answer Key.pdf
 
PSP LAB MANUAL.pdf
PSP LAB MANUAL.pdfPSP LAB MANUAL.pdf
PSP LAB MANUAL.pdf
 
18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdf18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdf
 
DS LAB MANUAL.pdf
DS LAB MANUAL.pdfDS LAB MANUAL.pdf
DS LAB MANUAL.pdf
 
CAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptxCAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptx
 
[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx
 
CAT-1 Answer Key.doc
CAT-1 Answer Key.docCAT-1 Answer Key.doc
CAT-1 Answer Key.doc
 
Unit 3 Complete.pptx
Unit 3 Complete.pptxUnit 3 Complete.pptx
Unit 3 Complete.pptx
 
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
 

Recently uploaded

AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
DuvanRamosGarzon1
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
Kamal Acharya
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
Kamal Acharya
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
PrashantGoswami42
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 

Recently uploaded (20)

AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 

Trees

  • 1. UNIT II : TREES By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Data Structures and Algorithm Analysis in C by Mark Allen Weiss & Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST32 – Data Structures
  • 2. Syllabus – Unit Wise 4/6/2022 2.1 _ Trees Preliminaries 2
  • 3. List of Exercises 4/6/2022 2.1 _ Trees Preliminaries 3
  • 4. Text Book and Reference Book 4/6/2022 2.1 _ Trees Preliminaries 4
  • 5. Unit II : Contents 1. Implementation of trees 2. Tree Traversals with an Application 3. Binary trees: Implementation 4. Expression trees 5. The Search Tree ADT: Binary Search Trees – Construction – Searching – Insertion – Deletion – Find Min – Find Max 6. AVL trees – Rotation – Insertion – Deletion. 4/6/2022 5 2.1 _ Trees Preliminaries
  • 6. Introduction • For large amounts of input, the linear access time of linked lists is prohibitive. • In this unit we look at a simple data structure for which the running time of most operations is O(log n) on average. • We also sketch a conceptually simple modification to this data structure that guarantees the above time bound in the worst case and discuss a second modification that essentially gives an O(log n) running time per operation for a long sequence of instructions. 4/6/2022 2.1 _ Trees Preliminaries 6
  • 7. Tree Representation • Tree represents the nodes connected by edges. We will discuss binary tree or binary search tree specifically. • Binary Tree is a special data structure used for data storage purposes. • A binary tree has a special condition that each node can have a maximum of two children. • A binary tree has the benefits of both an ordered array and a linked list as search is as quick as in a sorted array and insertion or deletion operation are as fast as in linked list. 4/6/2022 2.1 _ Trees Preliminaries 7
  • 8. Trees • The data structure that we are referring to is known as a binary search tree. • Trees in general are very useful abstractions in computer science. • Advantages: – trees are used to implement the file system of several popular operating systems. – trees can be used to evaluate arithmetic expressions. – trees to support searching operations in O(log n) average time. 4/6/2022 2.1 _ Trees Preliminaries 8
  • 9. Trees • A tree can be defined in several ways. • One natural way to define a tree is recursively. • A tree is a collection of nodes. • The collection can be empty, which is sometimes denoted as A. • Otherwise, a tree consists of a distinguished node r, called the root, and zero or more (sub)trees T1, T2, . . . , Tk, each of whose roots are connected by a directed edge to r. • The root of each subtree is said to be a child of r, and r is the parent of each subtree root. • From the recursive definition, we find that a tree is a collection of n nodes, • one of which is the root, and n - 1 edges 4/6/2022 2.1 _ Trees Preliminaries 9
  • 10. Tree Terms • In the tree of Figure below, the root is A. • Node F has A as a parent and K, L, and M as children. • Each node may have an arbitrary number of children, possibly zero. • Nodes with no children are known as leaves; the leaves in the tree below are B, C, H, I, P, Q, K, L, M, and N. • Nodes with the same parent are siblings; thus K, L, and M are all siblings. • Grandparent and grandchild relations can be defined in a similar manner. • A path from node n1 to nk is defined as a sequence of nodes n1, n2, . . . , nk. • The length of this path is the number of edges on the path, namely k -1. There is a path of length zero from every node to itself. • Notice that in a tree there is exactly one path from the root to each node. 4/6/2022 2.1 _ Trees Preliminaries 10
  • 11. Tree Terms • For any node ni, the depth of ni is the length of the unique path from the root to ni. Thus, the root is at depth 0. • The height of ni is the longest path from ni to a leaf. Thus all leaves are at height 0. • The height of a tree is equal to the height of the root. • For the tree in previous Figure, – E is at depth 1 and height 2; – F is at depth 1 and height 1; – the height of the tree is 3. • The depth of a tree is equal to the depth of the deepest leaf; this is always equal to the height of the tree. • If there is a path from n1 to n2, then n1 is an ancestor of n2 and n2 is a descendant of n1. If n1=n2, then n1 is a proper ancestor of n2 and n2 is a proper descendant of n1. 4/6/2022 2.1 _ Trees Preliminaries 11
  • 12. Tree Representation 4/6/2022 2.1 _ Trees Preliminaries 12
  • 13. Tree Terms • Path − Path refers to the sequence of nodes along the edges of a tree. • Root − The node at the top of the tree is called root. There is only one root per tree and one path from the root node to any node. • Parent − Any node except the root node has one edge upward to a node called parent. • Child − The node below a given node connected by its edge downward is called its child node. • Leaf − The node which does not have any child node is called the leaf node. • Subtree − Subtree represents the descendants of a node. • Visiting − Visiting refers to checking the value of a node when control is on the node. • Traversing − Traversing means passing through nodes in a specific order. • Levels − Level of a node represents the generation of a node. If the root node is at level 0, then its next child node is at level 1, its grandchild is at level 2, and so on. • keys − Key represents a value of a node based on which a search operation is to be carried out for a node. 4/6/2022 2.1 _ Trees Preliminaries 13
  • 14. Thank you 4/6/2022 2.1 _ Trees Preliminaries 14
  • 15. UNIT II : TREES By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Data Structures and Algorithm Analysis in C by Mark Allen Weiss & Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST32 – Data Structures
  • 16. Unit II : Contents 1. Implementation of trees 2. Tree Traversals with an Application 3. Binary trees: Implementation 4. Expression trees 5. The Search Tree ADT: Binary Search Trees – Construction – Searching – Insertion – Deletion – Find Min – Find Max 6. AVL trees – Rotation – Insertion – Deletion. 4/6/2022 16 2.2 _ Tree Traversals
  • 17. Tree Traversal • Traversal is a process to visit all the nodes of a tree and may print their values too. • Because, all nodes are connected via edges (links) we always start from the root (head) node. • That is, we cannot randomly access a node in a tree. • There are three ways which we use to traverse a tree − – In-order Traversal – Pre-order Traversal – Post-order Traversal • Generally, we traverse a tree to search or locate a given item or key in the tree or to print all the values it contains. 4/6/2022 2.2 _ Tree Traversals 17
  • 18. In-order Traversal • In this traversal method, – the left subtree is visited first, – then the root and – later the right sub-tree. • We should always remember that every node may represent a subtree itself. • If a binary tree is traversed in-order, the output will produce sorted key values in an ascending order. 4/6/2022 2.2 _ Tree Traversals 18
  • 19. In-order Traversal 4/6/2022 2.2 _ Tree Traversals 19 • We start from A, and following in-order traversal, we move to its left subtree B. • B is also traversed in-order. • The process goes on until all the nodes are visited. •The output of inorder traversal of this tree will be − D → B → E → A → F → C → G
  • 20. In-order Traversal – Algorithm & Code • Until all nodes are traversed • Step 1 − Recursively traverse left subtree. • Step 2 − Visit root node. • Step 3 − Recursively traverse right subtree. 4/6/2022 2.2 _ Tree Traversals 20 void inorder_traversal(struct node* root) { if(root != NULL) { inorder_traversal(root->leftChild); printf("%d ",root->data); inorder_traversal(root->rightChild); } }
  • 21. Pre-order Traversal • In this traversal method, – the root node is visited first, – then the left subtree and – finally the right subtree. 4/6/2022 2.2 _ Tree Traversals 21
  • 22. Pre-order Traversal 4/6/2022 2.2 _ Tree Traversals 22 • We start from A, and following pre-order traversal, we first visit A itself and then move to its left subtree B. • B is also traversed pre-order. • The process goes on until all the nodes are visited. •The output of pre-order traversal of this tree will be − A → B → D → E → C → F → G
  • 23. Pre-order Traversal – Algorithm & Code • Until all nodes are traversed • Step 1 − Visit root node. • Step 2 − Recursively traverse left subtree. • Step 3 − Recursively traverse right subtree. 4/6/2022 2.2 _ Tree Traversals 23 void preorder_traversal(struct node* root) { if(root != NULL) { printf("%d ",root->data); preorder_traversal(root->leftChild); preorder_traversal(root->rightChild); } }
  • 24. Post-order Traversal • In this traversal method, the root node is visited last, hence the name. – First we traverse the left subtree, – then the right subtree and – finally the root node. 4/6/2022 2.2 _ Tree Traversals 24
  • 25. Post-order Traversal 4/6/2022 2.2 _ Tree Traversals 25 •We start from A, and following Post-order traversal, we first visit the left subtree B. •B is also traversed post-order. •The process goes on until all the nodes are visited. •The output of post-order traversal of this tree will be − D → E → B → F → G → C → A
  • 26. Post-order Traversal – Algorithm & Code • Until all nodes are traversed • Step 1 − Recursively traverse left subtree. • Step 2 − Recursively traverse right subtree. • Step 3 − Visit root node. 4/6/2022 2.2 _ Tree Traversals 26 void postorder_traversal(struct node* root) { if(root != NULL) { postorder_traversal(root->leftChild); postorder_traversal(root->rightChild); printf("%d ",root->data); } }
  • 27. Program to Implement Tree Traversal 4/6/2022 2.2 _ Tree Traversals 27
  • 28. 4/6/2022 2.2 _ Tree Traversals 28
  • 29. 4/6/2022 2.2 _ Tree Traversals 29
  • 30. 4/6/2022 2.2 _ Tree Traversals 30
  • 31. 4/6/2022 2.2 _ Tree Traversals 31
  • 32. 4/6/2022 2.2 _ Tree Traversals 32
  • 33. 4/6/2022 2.2 _ Tree Traversals 33
  • 34. 4/6/2022 2.2 _ Tree Traversals 34
  • 35. Thank you 4/6/2022 2.2 _ Tree Traversals 35
  • 36. UNIT II : TREES By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Data Structures and Algorithm Analysis in C by Mark Allen Weiss & Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST32 – Data Structures
  • 37. Unit II : Contents 1. Implementation of trees 2. Tree Traversals with an Application 3. Binary trees: Implementation 4. Expression trees 5. The Search Tree ADT: Binary Search Trees – Construction – Searching – Insertion – Deletion – Find Min – Find Max 6. AVL trees – Rotation – Insertion – Deletion. 4/6/2022 37 2.3 _ Binary Tree
  • 38. Binary Vs Binary Search Tree 4/6/2022 2.3 _ Binary Tree 38
  • 39. Binary Tree • A tree whose elements have at most 2 children is called a binary tree. • Since each element in a binary tree can have only 2 children, we typically name them the left and right child. 4/6/2022 2.3 _ Binary Tree 39
  • 40. Binary Tree - Examples 4/6/2022 2.3 _ Binary Tree 40
  • 41. Binary Search Tree • Binary Search Tree is a node-based binary tree data structure which has the following properties: – 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. – There must be no duplicate nodes. 4/6/2022 2.3 _ Binary Tree 41
  • 42. Binary Tree Vs Binary Search Tree 4/6/2022 2.3 _ Binary Tree 42
  • 43. Types of Binary Tree • Full/Proper/Strict Binary Tree • Complete Binary Tree • Perfect Binary Tree • Degenerate / Pathological Binary Tree – Left Skewed – Right Skewed – Pathological • Balanced Binary Tree 4/6/2022 2.3 _ Binary Tree 43
  • 44. Full/Proper/Strict Binary Tree • The full binary tree is also known as a strict binary tree. • The tree can only be considered as the full binary tree if each node must contain either 0 or 2 children. • OR • The full binary tree can also be defined as the tree in which each node must contain 2 children except the leaf nodes. 4/6/2022 2.3 _ Binary Tree 44
  • 45. Example- Full/Proper/Strict Binary Tree 4/6/2022 2.3 _ Binary Tree 45
  • 46. Full Binary Tree - Example 4/6/2022 2.3 _ Binary Tree 46
  • 47. Complete Binary Tree • The complete binary tree is a tree in which all the nodes are completely filled except the last level. • In the last level, all the nodes must be as left as possible. • In a complete binary tree, the nodes should be added from the left. • Let's create a complete binary tree. 4/6/2022 2.3 _ Binary Tree 47
  • 48. Example – Complete Binary Tree 4/6/2022 2.3 _ Binary Tree 48
  • 49. Complete Binary Tree - Example 4/6/2022 2.3 _ Binary Tree 49
  • 50. Perfect Binary Tree • A tree is a perfect binary tree if all the internal nodes have 2 children, and all the leaf nodes are at the same level. 4/6/2022 2.3 _ Binary Tree 50
  • 51. Perfect Binary Tree - Example 4/6/2022 2.3 _ Binary Tree 51
  • 52. Note: 4/6/2022 2.3 _ Binary Tree 52
  • 53. Degenerate Binary Tree • The degenerate binary tree is a tree in which all the internal nodes have only one children. 4/6/2022 2.3 _ Binary Tree 53 left-skewed tree right-skewed tree
  • 54. Degenerate Binary Tree - Example 4/6/2022 2.3 _ Binary Tree 54
  • 55. Balanced binary Tree • The balanced binary tree is a tree in which both the left and right trees differ by atmost 1. • For example, AVL and Red-Black trees are balanced binary tree. 4/6/2022 2.3 _ Binary Tree 55 This tree is a balanced binary tree because the difference between the left subtree and right subtree is zero.
  • 56. Balanced Binary Tree - Example 4/6/2022 2.3 _ Binary Tree 56 The above tree is not a balanced binary tree because the difference between the left subtree and the right subtree is greater than 1.
  • 57. To Find Height and Min/Max Nodes in Binary Tree • Depth of Node x: Length of path from root to Node x • Height of Node x: Number of edges in the longest path from node x to leaf node • Height of tree: Height of the tree is the height of the root • Level of node: Set of all nodes at a given depth is called the level of the tree • Trees with N nodes will have N-1 edges • Depth of root node is Zero • Root node is at level Zero • Height of leaf node is Zero • Height of tree with one node is Zero • An empty tree is also a valid binary tree • Every node except root is connected by a directed edge from exactly one node to other node and direction is: parent -> children 4/6/2022 2.3 _ Binary Tree 57
  • 58. Example 4/6/2022 2.3 _ Binary Tree 58
  • 59. Maximum and Minimum Number of Nodes of binary tree • Maximum number of nodes of binary tree of height “h” is 2h+1 - 1. 4/6/2022 2.3 _ Binary Tree 59
  • 60. • Minimum number of nodes of binary tree of height “h” is “h+1” 4/6/2022 2.3 _ Binary Tree 60
  • 61. Height of the binary tree with maximum and minimum nodes of binary tree 4/6/2022 2.3 _ Binary Tree 61 • Minimum height of the binary tree of with maximum number of nodes as “n” • For any binary tree of height “h”, maximum number of nodes = 2h+1 – 1 Here, Max nodes = n So, n = 2h+1 – 1 • => n + 1 = 2h+1 • Applying log on both sides, • =>log(n+1) = log2h+1 • => log(n+1) = (h+1) log2 • =>log(n+1)=(h+1) • =>Height of the binary with maximum “n” nodes => • h = ⌈ log(n+1) ⌉ - 1
  • 62. • Minimum height of the binary tree of with maximum number of nodes as “n” • For any binary tree of height “h”, minimum number of nodes = h + 1 • =>n=h+1 • =>Height of the binary with minimum “n” nodes => h = n-1 4/6/2022 2.3 _ Binary Tree 62
  • 63. 4/6/2022 2.3 _ Binary Tree 63
  • 64. Binary Tree Implementation - Program 4/6/2022 2.3 _ Binary Tree 64
  • 65. 4/6/2022 2.3 _ Binary Tree 65
  • 66. 4/6/2022 2.3 _ Binary Tree 66
  • 67. Thank you 4/6/2022 2.3 _ Binary Tree 67
  • 68. UNIT II : TREES By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Data Structures and Algorithm Analysis in C by Mark Allen Weiss & Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST32 – Data Structures
  • 69. Unit II : Contents 1. Implementation of trees 2. Tree Traversals with an Application 3. Binary trees: Implementation 4. Expression trees 5. The Search Tree ADT: Binary Search Trees – Construction – Searching – Insertion – Deletion – Find Min – Find Max 6. AVL trees – Rotation – Insertion – Deletion. 4/6/2022 69 2.4 _ Expression Tree
  • 70. Expression Tree • The expression tree is a binary tree in which each – internal node corresponds to the operator and – each leaf node corresponds to the operand. 4/6/2022 2.4 _ Expression Tree 70
  • 71. Expression Tree - Example • expression tree for 3 + ((5+9)*2) would be: 4/6/2022 2.4 _ Expression Tree 71
  • 72. Constructing an Expression Tree • First, convert infix to postfix. • Next, We read our expression one symbol at a time. – If the symbol is an operand, we create a one node tree and push a pointer to it onto a stack. – If the symbol is an operator, we pop pointers to two trees T1 and T2 from the stack (T1 is popped first) and form a new tree whose root is the operator and whose left and right children point to T2 and T1 respectively. A pointer to this new tree is then pushed onto the stack. 4/6/2022 2.4 _ Expression Tree 72
  • 73. Example • (a+b)*(c*(d+e)) • First, Convert Infix into postfix. – a b + c d e + * * 4/6/2022 2.4 _ Expression Tree 73
  • 74. Example (cntd.,) • The first two symbols are operands, so we create one-node trees and push pointers to them onto a stack.* 4/6/2022 2.4 _ Expression Tree 74 a b + c d e + * *
  • 75. Example (cntd.,) • Next, a '+' is read, so two pointers to trees are popped, a new tree is formed, and a pointer to it is pushed onto the stack.* 4/6/2022 2.4 _ Expression Tree 75 a b + c d e + * *
  • 76. Example (cntd.,) • Next, c, d, and e are read, and for each a one- node tree is created and a pointer to the corresponding tree is pushed onto the stack. 4/6/2022 2.4 _ Expression Tree 76 a b + c d e + * *
  • 77. Example (cntd.,) • Now a '+' is read, so two trees are merged. 4/6/2022 2.4 _ Expression Tree 77 a b + c d e + * *
  • 78. Example (cntd.,) • Continuing, a '*' is read, so we pop two tree pointers and form a new tree with a '*' as root. 4/6/2022 2.4 _ Expression Tree 78 a b + c d e + * *
  • 79. Example (cntd.,) • Finally, the last symbol is read, two trees are merged, and a pointer to the final tree is left on the stack. 4/6/2022 2.4 _ Expression Tree 79 a b + c d e + * *
  • 80. Thank you 4/6/2022 2.4 _ Expression Tree 80
  • 81. UNIT II : TREES By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Data Structures and Algorithm Analysis in C by Mark Allen Weiss & Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST32 – Data Structures
  • 82. Unit II : Contents 1. Implementation of trees 2. Tree Traversals with an Application 3. Binary trees: Implementation 4. Expression trees 5. The Search Tree ADT :Binary Search Trees – Construction – Searching – Find Min – Find Max – Insertion – Deletion 6. AVL trees – Rotation – Insertion – Deletion. 4/6/2022 82 2.5 _ Binary Search Tree
  • 83. Search Tree ADT • Search Tree ADT contains the following operations: – Construction – Searching – Insertion – Deletion – Find Min – Find Max 4/6/2022 2.5 _ Binary Search Tree 83
  • 84. Binary Search Tree • Binary Search tree exhibits a special behavior. • A node's – left child must have a value less than its parent's value and – right child must have a value greater than its parent value – The left and right subtree each must also be a binary search tree. – There must be no duplicate nodes. 4/6/2022 2.5 _ Binary Search Tree 84
  • 85. Binary Search Tree 4/6/2022 2.5 _ Binary Search Tree 85
  • 86. Tree Node • The code to write a tree node would be similar to what is given below. • It has a data part and references to its left and right child nodes. 4/6/2022 2.5 _ Binary Search Tree 86
  • 87. BST Basic Operations • The basic operations that can be performed on a binary search tree data structure, are the following − – Insert − Inserts an element in a tree/create a tree. – Search − Searches an element in a tree. – Preorder Traversal − Traverses a tree in a pre-order manner. – Inorder Traversal − Traverses a tree in an in-order manner. – Postorder Traversal − Traverses a tree in a post-order manner. 4/6/2022 2.5 _ Binary Search Tree 87
  • 88. Insertion Operation - BST • The very first insertion creates the tree. • Afterwards, whenever an element is to be inserted, first locate its proper location. • Start searching from the root node, – then if the data is less than the key value, – search for the empty location in the left subtree and – insert the data. • Otherwise, – search for the empty location in the right subtree and – insert the data. 4/6/2022 2.5 _ Binary Search Tree 88
  • 89. Insertion on BST - Algorithm 4/6/2022 2.5 _ Binary Search Tree 89
  • 90. Implementation – BST Insertion 4/6/2022 2.5 _ Binary Search Tree 90
  • 91. Implementation – BST Insertion 4/6/2022 2.5 _ Binary Search Tree 91
  • 92. Implementation – BST Insertion 4/6/2022 2.5 _ Binary Search Tree 92
  • 93. Search Operation - BST • Whenever an element is to be searched, – start searching from the root node, – then if the data is less than the key value, – search for the element in the left subtree. • Otherwise, – search for the element in the right subtree. • Follow the same algorithm for each node. 4/6/2022 2.5 _ Binary Search Tree 93
  • 94. Algorithm – Search on BST 4/6/2022 2.5 _ Binary Search Tree 94
  • 95. Implementation – Search on BST 4/6/2022 2.5 _ Binary Search Tree 95
  • 96. Find an element in BST • This operation requires returning a pointer to the node in tree T that has key X or NULL if there is no such node. • The find operation as follows. – Check whether the root is NULL if so then return NULL. – Otherwise, check the value X with the root node value (ie. T->Element) – If X is equal to T->Element, return T – If X is less than T->Element, traverse the left of T recursively. – If X is greater than T->Element, traverse the right of T recursively. 4/6/2022 2.5 _ Binary Search Tree 96
  • 97. Find • Position Find( ElementType 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; • } 4/6/2022 2.5 _ Binary Search Tree 97
  • 98. Example • To find an element 4 (X = 4) in the below tree – In the first fig, the element 4 is checked with root 6. 4 is less than 6. So goto the left subtree. – In the second fig, element 4 is checked with node 2. 4 is greater than 2. So goto the right subtree. – In the third fig, the element 4 is checked with node 4. The element is equal. So return 4. 4/6/2022 2.5 _ Binary Search Tree 98
  • 99. Find Min • This operation returns the position of the smallest element in the tree. • To find the minimum element, start at the root and go left as long as there is a left child. • The stopping point is the smallest element. 4/6/2022 2.5 _ Binary Search Tree 99
  • 100. Recursive / Non-recursive routine for Find Min 4/6/2022 2.5 _ Binary Search Tree 100
  • 101. Find Max • This operation returns the position of the largest element in the tree. • To find the maximum element, start at the root and go right as long as there is a right child. • The stopping point is the largest element. 4/6/2022 2.5 _ Binary Search Tree 101
  • 102. Recursive / Non-recursive routine for Find Max 4/6/2022 2.5 _ Binary Search Tree 102
  • 103. Insert • To insert the element X in to the tree, check with the root node T. • If it is less than the root, traverse the left sub tree recursively until it reaches the T->Left equals to NULL. Then X is placed in T->Left. • If it is greater than the root, traverse the right sub tree recursively until it reaches the T->Right equals to NULL. Then X is placed in T->Right. • If X is found in the tree, do nothing. 4/6/2022 2.5 _ Binary Search Tree 103
  • 104. Insert • SearchTree Insert( ElementType X, SearchTree T ) • { • if( T = = NULL ) • { /* Create and return a one-node tree */ • T = malloc ( sizeof (struct TreeNode) ); • if( T != NULL ) • { • T-Element = X; • T->Left = 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 ); • /* else X is in the tree already. We'll do nothing */ • return T; • } • } 4/6/2022 2.5 _ Binary Search Tree 104
  • 105. Example - To insert 8, 4, 1, 6, 5, 7, 10 • First insert element 8 which is considered as root. • Next insert element 4, 4 is less than 8, traverse towards left. 4/6/2022 2.5 _ Binary Search Tree 105
  • 106. Example - To insert 8, 4, 1, 6, 5, 7, 10 • Next insert element 1, 1<8 traverse towards left. 1<4 traverse towards left. • To insert element 6, 6<8 traverse towards left. 6>4, place it as right child of 4. • To insert element 5, 5<8 traverse towards left. 5>4, traverse towards right. 5<6, place it as left child of 6. 4/6/2022 2.5 _ Binary Search Tree 106
  • 107. Example - To insert 8, 4, 1, 6, 5, 7, 10 • To insert element 7, 7<8 traverse towards left. 7>4, traverse towards right. 7>6, place it as right child of 6. • To insert element 10, 10>8, place it as a right child of 8. 4/6/2022 2.5 _ Binary Search Tree 107
  • 108. Delete • While deleting a node from a tree, the memory is to be released. • Deletion operation is the complex operation in the binary search tree. • To delete a node from the tree consider the following three possibilities. – Case 1: Node to be deleted is a leaf node – Case 2: Node with one child. – Case 3: Node with two children. 4/6/2022 2.5 _ Binary Search Tree 108
  • 109. Case 1: Deleting the leaf node 1. Search the parent of the leaf node. 2. Make the parent link of the leaf node as NULL. 3. Release Memory. 4/6/2022 2.5 _ Binary Search Tree 109 Example: Deletion of node 6
  • 110. Case 2: Deleting the node with only one child. 4/6/2022 2.5 _ Binary Search Tree 110 1. Search the parent of the node to be deleted. 2. Assign the parent link to the child node of the node to be deleted. 3. Release the memory of the deleted node. 4. If a node has one child, it can be deleted by adjusting its parent pointer to point to its child node. Eg. Deletion of a node (4) with one child, before and after
  • 111. Case 3: Deleting a node with two children. 4/6/2022 2.5 _ Binary Search Tree 111 • Inorder to delete a node with two children, it can be replaced by a node whose key is larger than any node in P‟s right sub tree to preserve the Binary Search Tree property. • The possible nodes that could replace node P are – Rule 1: The node with the largest value in P‟s left sub tree. – Rule 2: The node with the smallest value in P‟s right sub tree. Eg: Deletion of a node 4 with two children, before and after
  • 112. Delete 4/6/2022 2.5 _ Binary Search Tree 112 • SearchTree Delete( ElementType X, SearchTree T ) • { • Position TmpCell; • if( T = = NULL ) • Error("Element not found"); else • if( X < T->Element ) /* Go left */ • T->Left = Delete( X, T->Left ); • else • if( X > T->Element ) /* Go right */ • T->Right = Delete( X, T->Right ); • else /* Found element to be deleted */ • if( T->Left && T->Right ) /* Two children */ • { /* Replace with smallest in right subtree */ • TmpCell = FindMin( T->Right ); • T->Element = TmpCell->Element; • T->Right = Delete( T->Element, T->Right ); • } • else /* One or zero child */ • { • TmpCell = T; • if( T->Left = = NULL ) /* Only a right child */ • T = T->Right; • if( T->Right = = NULL ) /* Only a left child */ • T = T->Left; • free(TmpCell ); • } • return T; • }
  • 113. BST • How many distinct binary search trees can be created out of 3 distinct keys? 4/6/2022 2.5 _ Binary Search Tree 113
  • 114. Thank you 4/6/2022 2.5 _ Binary Search Tree 114
  • 115. UNIT II : TREES By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Data Structures and Algorithm Analysis in C by Mark Allen Weiss & Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST32 – Data Structures
  • 116. Unit II : Contents 1. Implementation of trees 2. Tree Traversals with an Application 3. Binary trees: Implementation 4. Expression trees 5. The Search Tree ADT :Binary Search Trees – Construction – Searching – Find Min – Find Max – Insertion – Deletion 6. AVL trees – Rotation – Insertion – Deletion 4/6/2022 116 2.6 _ AVL Trees
  • 117. AVL Tree • AVL Tree is invented by GM Adelson - Velsky and EM Landis in 1962. The tree is named AVL in honour of its inventors. • An AVL (Adelson-Velskii and Landis) tree is a binary search tree with a balance condition. • AVL Tree can be defined as height balanced binary search tree in which each node is associated with a balance factor which is calculated by subtracting the height of its right sub-tree from that of its left sub-tree. • The balance condition must be easy to maintain, and it ensures that the depth of the tree is O(log n). • The simplest idea is to require that the left and right subtrees have the same height. 4/6/2022 2.6 _ AVL Trees 117
  • 118. Balancing Factor • Balancing factor is -1,0,1 • If balance factor of any node is 1, it means that the left sub-tree is one level higher than the right sub-tree. • If balance factor of any node is 0, it means that the left sub-tree and right sub-tree contain equal height. • If balance factor of any node is -1, it means that the left sub-tree is one level lower than the right sub-tree. 4/6/2022 2.6 _ AVL Trees 118
  • 119. Example – AVL Tree 4/6/2022 2.6 _ AVL Trees 119
  • 120. Why AVL Tree? • AVL tree controls the height of the binary search tree by not letting it to be skewed. • The time taken for all operations in a binary search tree of height h is O(h). • However, it can be extended to O(n) if the BST becomes skewed (i.e. worst case). • By limiting this height to log n, AVL tree imposes an upper bound on each operation to be O(log n) where n is the number of nodes. 4/6/2022 2.6 _ AVL Trees 120
  • 121. Time Complexity 4/6/2022 2.6 _ AVL Trees 121
  • 122. Operations on AVL tree • Due to the fact that, AVL tree is also a binary search tree therefore, all the operations are performed in the same way as they are performed in a binary search tree. – Searching and traversing do not lead to the violation in property of AVL tree. – However, insertion and deletion are the operations which can violate this property and therefore, they need to be revisited. 4/6/2022 2.6 _ AVL Trees 122
  • 123. AVL Tree - Rotations 4/6/2022 2.6 _ AVL Trees 123
  • 124. AVL Tree - Rotations • If the balance factor of any node in an AVL tree becomes less than -1 or greater than 1, the tree has to be balanced by making a simple modifications in the tree called rotation. • An AVL tree causes imbalance, when any one of the following conditions occur. α – is the node must be rebalanced. – Case 1: An insertion from the left sub tree of the left child of node α. [LL Rotation] – Case 2: An insertion into the right sub tree of the left child of α. [LR Rotation] – Case 3: An insertion into the left sub tree of the right child of α. [RL Rotation] – Case 4: An insertion into the right sub tree of the right child of α. [RR Rotation] • These imbalances can be overcome by – Single Rotation – Double Rotation • Case 1 and Case 4 imbalance (left – left or right – right) is fixed by a single rotation of the tree. • Case 2 and Case 3 imbalance (left – right or right – left) is fixed by double rotation. 4/6/2022 2.6 _ AVL Trees 124
  • 125. LL Rotation • When BST becomes unbalanced, due to a node is inserted into the left subtree of the left subtree of C, then we perform LL rotation. • LL rotation is clockwise rotation, which is applied on the edge below a node having balance factor 2. 4/6/2022 2.6 _ AVL Trees 125
  • 126. RR Rotation • When BST becomes unbalanced, due to a node is inserted into the right subtree of the right subtree of A, then we perform RR rotation. • RR rotation is an anticlockwise rotation, which is applied on the edge below a node having balance factor -2. 4/6/2022 2.6 _ AVL Trees 126
  • 127. LR Rotation • Double rotations are bit tougher than single rotation which has already explained above. • LR rotation = RR rotation + LL rotation • i.e., first RR rotation is performed on subtree and then LL rotation is performed on full tree, • Here the full tree we mean the first node from the path of inserted node whose balance factor is other than -1, 0, or 1. 4/6/2022 2.6 _ AVL Trees 127
  • 128. LR Rotation 4/6/2022 2.6 _ AVL Trees 128
  • 129. RL Rotation 4/6/2022 2.6 _ AVL Trees 129 • As already discussed, that double rotations are bit tougher than single rotation which has already explained above. • R L rotation = LL rotation + RR rotation • i.e., first LL rotation is performed on subtree and then RR rotation is performed on full tree, • Here the full tree we mean the first node from the path of inserted node whose balance factor is other than -1, 0, or 1.
  • 130. RL Rotation 4/6/2022 2.6 _ AVL Trees 130
  • 131. AVL Tree - Insertion • In an AVL tree, the insertion operation is performed with O(log n) time complexity. • In AVL Tree, a new node is always inserted as a leaf node. • The insertion operation is performed as follows... – Step 1 - Insert the new element into the tree using Binary Search Tree insertion logic. – Step 2 - After insertion, check the Balance Factor of every node. – Step 3 - If the Balance Factor of every node is 0 or 1 or - 1 then go for next operation. – Step 4 - If the Balance Factor of any node is other than 0 or 1 or -1 then that tree is said to be imbalanced. In this case, perform suitable Rotation to make it balanced and go for next operation. 4/6/2022 2.6 _ AVL Trees 131
  • 132. AVL Tree Example – 51,26,11,6,8,4,31 4/6/2022 2.6 _ AVL Trees 132
  • 133. AVL Tree - Deletion • The deletion operation in AVL Tree is similar to deletion operation in BST. • But after every deletion operation, we need to check with the Balance Factor condition. • If the tree is balanced after deletion go for next operation otherwise perform suitable rotation to make the tree Balanced. 4/6/2022 2.6 _ AVL Trees 133
  • 134. 4/6/2022 2.6 _ AVL Trees 134
  • 135. 4/6/2022 2.6 _ AVL Trees 135
  • 136. 4/6/2022 2.6 _ AVL Trees 136
  • 137. 4/6/2022 2.6 _ AVL Trees 137
  • 138. 4/6/2022 2.6 _ AVL Trees 138
  • 139. 4/6/2022 2.6 _ AVL Trees 139
  • 140. 4/6/2022 2.6 _ AVL Trees 140
  • 141. Thank you 4/6/2022 2.6 _ AVL Trees 141