Tree

You might also like

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

TREE

Mr. Mahendra Pratap Yadav


Assistant Professor
School of Computing Science and Engineering
VIT Bhopal University
mahendra.pratap@vitbhopal.ac.in
Tree
•Tree data structure may be defined as-

Tree is a non-linear data structure which organizes data in a


hierarchical structure and this is a recursive definition.
OR
A tree is a connected graph without any circuits.
OR
If in a graph, there is one and only one path between every pair
of vertices, then graph is called as a tree.

2
Tree
Definition (recursively): A tree is a finite set of one
or more nodes such that
There is a specially designated node called root.
The remaining nodes are partitioned into n>=0 disjoint set
T1,…,Tn, where each of these sets is a tree. T1,…,Tn are called
the subtrees of the root.
Every node in the tree is the root of some subtree
Tree

5/4/2022 CS 201
Tree:-Properties
•The important properties of tree data structure are-

•There is one and only one path between every pair of vertices
in a tree.

•A tree with n vertices has exactly (n-1) edges.

•A graph is a tree if and only if it is minimally connected.

•Any connected graph with n vertices and (n-1) edges is a tree.

5
Tree Terminology-
The important terms related to tree data structure are-

6
Tree:-Root
•The first node from where the tree originates is called as
a root node.
• In any tree, there must be only one root node.
•We can never have multiple root nodes in a tree data
structure.

Example

7
Tree:- Edge
•The connecting link between any two nodes is called as
an edge.
• In a tree with n number of nodes, there are exactly (n-1)
number of edges.

Example

8
Tree:- Parent
•The node which has a branch from it to any other node is
called as a parent node.
• In other words, the node which has one or more children is
called as a parent node.
• In a tree, a parent node can have any number of child nodes.

Example

9
Tree:- Parent

Here,

•Node A is the parent of nodes B and C


•Node B is the parent of nodes D, E and F
•Node C is the parent of nodes G and H
•Node E is the parent of nodes I and J
•Node G is the parent of node K

10
Tree:- Child
•The node which is a descendant of some node is called as
a child node.
•All the nodes except root node are child nodes.

Example

11
Tree:- Child

Here,

•Nodes B and C are the children of node A


•Nodes D, E and F are the children of node B
•Nodes G and H are the children of node C
•Nodes I and J are the children of node E
•Node K is the child of node G

12
Tree:- Siblings
•Nodes which belong to the same parent are called as siblings.
•In other words, nodes with the same parent are sibling nodes.

Example

13
Tree:- Sibling

Here,

•Nodes B and C are siblings


•Nodes D, E and F are siblings
•Nodes G and H are siblings
•Nodes I and J are siblings

14
Tree:- Degree
•Degree of a node is the total number of children of that node.
•Degree of a tree is the highest degree of a node among all the
nodes in the tree.

Example

15
Tree:- Degree
Here,
•Degree of node A = 2
•Degree of node B = 3
•Degree of node C = 2
•Degree of node D = 0
•Degree of node E = 2
•Degree of node F = 0
•Degree of node G = 1
•Degree of node H = 0
•Degree of node I = 0
•Degree of node J = 0
•Degree of node K = 0

16
Tree:- Internal Node
•The node which has at least one child is called as an internal
node.
•Internal nodes are also called as non-terminal nodes.
•Every non-leaf node is an internal node.

Example

Here, nodes A, B, C, E and G are internal nodes. 17


Tree:- Leaf Node
•The node which does not have any child is called as a leaf
node.
•Leaf nodes are also called as external nodes or terminal
nodes.

Example

Here, nodes D, I, J, F, K and H are leaf nodes. 18


Tree:- Level
•In a tree, each step from top to bottom is called as level of a
tree.
•The level count starts with 0 and increments by 1 at each level
or step.

Example

19
Tree:- Height
•Total number of edges that lies on the longest path from any
leaf node to a particular node is called as height of that node.
• Height of a tree is the height of root node.
•Height of all leaf nodes = 0

Example

20
Tree:- Height
Here, •Height of node A = 3
•Height of node B = 2
•Height of node C = 2
•Height of node D = 0
•Height of node E = 1
•Height of node F = 0
•Height of node G = 1
•Height of node H = 0
•Height of node I = 0
•Height of node J = 0
•Height of node K = 0

21
Tree:- Depth
•Total number of edges from root node to a particular node is
called as depth of that node.
•Depth of a tree is the total number of edges from root node to
a leaf node in the longest path.
Example

22
Tree:- Depth
•Depth of the root node = 0
•The terms “level” and “depth” are used interchangeably.

Here
• Depth of node A = 0
•Depth of node B = 1
•Depth of node C = 1
•Depth of node D = 2
•Depth of node E = 2
•Depth of node F = 2
•Depth of node G = 2
•Depth of node H = 2
•Depth of node I = 3
•Depth of node J = 3
•Depth of node K = 3
23
Tree:- Subtree
•In a tree, each child from a node forms a subtree recursively.
•Every child node forms a subtree on its parent node.
Example

24
Tree:- Forest
•A forest is a set of disjoint trees.
Example

25
Binary Tree
Binary Tree is a rooted tree in which
root can have maximum two children
such that each of them is again a binary
tree. That means, there can be 0,1, or 2
children of any node.
Binary Tree
Binary Trees
The abstract data type of binary tree
Strict Binary Tree
Strict Binary Tree is a Binary tree in
which root can have exactly two
children or no children at all. That
means, there can be 0 or 2 children of
any node.
Strict Binary Tree
Binary Trees
Two special kinds of binary trees:
(a) skewed tree, (b) complete binary tree
The all leaf nodes of these trees are on two adjacent levels
Binary Trees
Properties of binary trees
Lemma 5.1 [Maximum number of nodes]:
1. The maximum number of nodes on level i of a binary tree
is 2i-1, i 1.
2. The maximum number of nodes in a binary tree of depth k
is 2k-1, k1.
Lemma 5.2 [Relation between number of leaf nodes and
degree-2 nodes]:
For any nonempty binary tree, T, if n0 is the number of leaf
nodes and n2 is the number of nodes of degree 2, then n0
= n2 + 1.
These lemmas allow us to define full and complete
binary trees
Binary Trees
Definition:
A full binary tree of depth k is a binary tree of death k having 2k-1
nodes, k  0.
A binary tree with n nodes and depth k is complete iff its nodes
correspond to the nodes numbered from 1 to n in the full binary
tree of depth k.
From Lemma 5.1, the
height of a complete
binary tree with n nodes
is log2(n+1)
Complete Binary Tree
Complete Binary Tree is a Strict Binary
tree in which every leaf node is at same
level. That means, there are equal
number of children in right and left
subtree for every node.
Complete Binary Tree
Extended Binary Tree
⚫ A binary tree with special nodes replacing every null
subtree. Every regular node has two children, and
every special node has no children.
Extended Binary Tree
⚫ An extended binary tree is a transformation of
any binary tree into a complete binary tree.

⚫ This transformation consists of replacing every null


subtree of the original tree with “special nodes.”

⚫ The nodes from the original tree are then called as


internal nodes, while the “special nodes” are called as
external nodes.
Binary Tree Traversals
Many algorithms require all nodes of a binary tree be
visited and the contents of each node processed or
examined.
There are 3 traditional types of traversals
preorder traversal: process the root, then process all sub trees
(left to right)
in order traversal: process the left sub tree, process the root,
process the right sub tree
post order traversal: process the left sub tree, process the right
sub tree, then process the root

Binary Trees 38
Binary Trees
Binary tree representations (using array)
Lemma 5.3: If a complete binary tree with n nodes is
represented sequentially, then for any node with index i,
1  i  n, we have
1. parent(i) is at i /2 if i  1.
If i = 1, i is at the root and has no parent.
2. LeftChild(i) is at 2i if 2i  n.
If 2i  n, then i has no left child.
3. RightChild(i) is at 2i+1 if 2i+1  n.
A 1
If 2i +1  n, then i has no left child

[1] [2] [3] [4] [5] [6] [7] B 2 C 3


A B C — D — E
Level 1 D E
Level 2 Level 3 4 5 6 7
Binary Tree Representation
⚫ Array representation.
⚫ Linked representation.
Array Representation
⚫ Number the nodes using the numbering scheme for a
full binary tree. The node that is numbered i is stored in
tree[i].
a1

2 3
b c

4 5 6 7
d e f g
8 9 10
h i j

tree[] a b c d e f g h i j
0 5 10
Binary Trees
Binary tree representations (using array)
Waste spaces: in the worst case, a skewed tree of depth k
requires 2k-1 spaces. Of these, only k spaces will be occupied
Insertion or deletion
of nodes from the
middle of a tree
requires the
movement of
potentially many nodes
to reflect the change in
the level of these nodes
Right-Skewed Binary Tree
a1
b 3
7
c
15
d

tree[] a - b - - - c - - - - - - - d
0 5 10 15

⚫ An n node binary tree needs an array whose


length is between n+1 and 2n.
Linked Representation
⚫ Each binary tree node is represented as an object
whose data type is BinaryTreeNode.
⚫ The space required by an n node binary tree is n *
(space required by one node).
Link Representation
of Binary Tree
typedef struct node
{
int data;
struct node *lc,*rc;
};
Linked Representation Example
root a

b c

d e

g
f
leftChild
h
rightChild
Binary Trees
Binary tree representations (using link)
Binary Trees
Binary tree representations (using link)
Binary Tree Traversals
How to traverse a tree or visit each node in the tree
exactly once?
There are six possible combinations of traversal
LVR, LRV, VLR, VRL, RVL, RLV
Adopt convention that we traverse left before
right, only 3 traversals remain
LVR (inorder), LRV (postorder), VLR (preorder)

left_child data right_child


V
L: moving left : R: moving right
visiting
node
Binary Tree Traversals
Arithmetic Expression using binary tree
inorder traversal (infix expression)
A/B*C*D+E
preorder traversal (prefix expression)
+**/ABCDE
postorder traversal
(postfix expression)
AB/C*D*E+
level order traversal
+*E*D/CAB
Binary Tree Traversals
Inorder traversal (LVR) (recursive version)

output: A / B * C * D + E

ptr
L
V
R
Binary Tree Traversals (4/9)
Preorder traversal (VLR) (recursive version)

output: + * * / A B C D E

V
L
R
Binary Tree Traversals (5/9)
Postorder traversal (LRV) (recursive version)

output: A B / C * D * E +

L
R
V
Binary Tree Traversals (6/9)
Iterative inorder traversal
we use a stack to simulate recursion
5 4 11
8 3 14
2 17
1
A B
/ *C * E+
D

L
V

output: A /B *C *D + E node
Binary Tree Traversals
Analysis of inorder2 (Non-recursive Inorder traversal)
Let n be the number of nodes in the tree
Time complexity: O(n)
Every node of the tree is placed on and removed
from the stack exactly once
Space complexity: O(n)
equal to the depth of the tree which
(skewed tree is the worst case)
Binary Tree Traversals
Level-order traversal
method:
We visit the root first, then the root’s left child, followed by the root’s
right child.
We continue in this manner, visiting the nodes at each new level from
the leftmost node to the rightmost nodes
This traversal requires a queue to implement
Binary Tree Traversals
Level-order traversal (using queue)

output: + * E * D / C A B
1 17 3 14 4 11 5
2 8
*+ E * D / C A B

FIFO

ptr
Additional Binary Tree Operations

node structure
For the purpose of our evaluation algorithm, we assume each
node has four fields:

We define this node structure in C as:


Results of Traversals
To determine the results of a traversal on a given tree draw
a path around the tree.
start on the left side of the root and trace around the tree. The path should stay close
to the tree.

12 pre order: process when


pass down left side of node
12 49 13 5 42
in order: process when pass
49 42
underneath node
13 49 5 12 42
13 5 post order: process when
pass up right side of node
13 5 49 42 12
CS314 Binary Trees 59
Tree Traversal : Pre order
⚫ Pre order (N L R)
Tree Traversal : Pre order
⚫ Pre order (N L R)
A
Tree Traversal : Pre order
⚫ Pre order (N L R)
A, B
Tree Traversal : Pre order
⚫ Pre order (N L R)
A, B, D
Tree Traversal : Pre order
⚫ Pre order (N L R)
A, B, D, E
Tree Traversal : Pre order
⚫ Pre order (N L R)
A, B, D, E, C
Tree Traversal : Pre order
⚫ Pre order (N L R)
A, B, D, E, C, F
Tree Traversal : Pre order
⚫ Pre order (N L R)
A, B, D, E, C, F, G
Tree Traversal : In order
⚫ In order (L N R)
Tree Traversal : In order
⚫ In order (L N R)
D
Tree Traversal : In order
⚫ In order (L N R)
D, B
Tree Traversal : In order
⚫ In order (L N R)
D, B, E
Tree Traversal : In order
⚫ In order (L N R)
D, B, E, A
Tree Traversal : In order
⚫ In order (L N R)
D, B, E, A, F
Tree Traversal : In order
⚫ In order (L N R)
D, B, E, A, F, C
Tree Traversal : In order
⚫ In order (L N R)
D, B, E, A, F, C, G
Tree Traversal : Post order
⚫ Post order (L R N)
Tree Traversal : Post order
⚫ Post order (L R N)
D
Tree Traversal : Post order
⚫ Post order (L R N)
D, E
Tree Traversal : Post order
⚫ Post order (L R N)
D, E, B
Tree Traversal : Post order
⚫ Post order (L R N)
D, E, B, F
Tree Traversal : Post order
⚫ Post order (L R N)
D, E, B, F, G
Tree Traversal : Post order
⚫ Post order (L R N)
D, E, B, F, G, C
Tree Traversal : Post order
⚫ Post order (L R N)
D, E, B, F, G, C, A
Constructing Binary Tree
⚫ In order – D, G, B, H, E, A, F, I, C
⚫ Pre order – A, B, D, G, E, H, C, F, I

⚫ Step 1 : finding the root


⚫ Root Node – A (from pre order)
⚫ Step 2 : Find left and right part of the root
⚫ Left part -

⚫ Right part -
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Threaded Binary Trees
Threads
Do you find any drawback of the above tree?
Too many null pointers in current representation of binary
trees
n: number of nodes
number of non-null links: n-1
total links: 2n
null links: 2n-(n-1) = n+1
Solution: replace these null pointers with some useful
“threads”
Threaded Binary Trees
Threads
Threads; Threading Consider again the linked representation
of a binary tree T. Approximately half of the entries in the
pointer fields LEFT and RIGHT will contain null elements.
This space may be more efficiently used by replacing the null
entries by some other type of information.

Specifically, we will replace certain null entries by special


pointers which point to nodes higher in the tree. These special
pointers are called threads, and binary trees with such
pointers are called threaded trees.
Threaded Binary Trees
Threads
Threaded Binary Trees
One-way inorder threads
Threaded Binary Trees
Two-way inorder threads
Threaded Binary Trees
Two-way inorder threads with header node
Threaded Binary Trees
Rules for constructing the threads
If ptr->left_child is null,
replace it with a pointer to the node that would be visited
before ptr in an inorder traversal
If ptr->right_child is null,
replace it with a pointer to the node that would be visited
after ptr in an inorder traversal
Threaded Binary Trees
A Threaded Binary Tree

root A
t: true  thread
f: false  child
dangling
f B f C

D t E t F G
dangling

inorder traversal:
H I
H D I B E A F C G
Threaded Binary
Trees
Two additional fields of the node structure,
left-thread and right-thread
If ptr->left-thread=TRUE,
then ptr->left-child contains a thread;
Otherwise it contains a pointer to the left child.
Similarly for the right-thread
Threaded Binary Trees
If we don’t want the left pointer of H and the right
pointer of G to be dangling pointers, we may create
root node and assign them pointing to the root node
Threaded Binary Trees
Inorder traversal of a threaded binary tree
By using of threads we can perform an inorder traversal
without making use of a stack (simplifying the task)
Now, we can follow the thread of any node, ptr, to the “next”
node of inorder traversal
1. If ptr->right_thread = TRUE, the inorder successor of ptr is
ptr->right_child by definition of the threads
2. Otherwise we obtain the inorder successor of ptr by
following a path of left-child links from the right-child of
ptr until we reach a node with left_thread = TRUE
Threaded Binary Trees
Finding the inorder successor (next node) of a node
threaded_pointer insucc(threaded_pointer tree){
threaded_pointer temp;
temp = tree->right_child;
if (!tree->right_thread) tree
while (!temp->left_thread)
temp = temp->left_child;
return temp;
}
temp

Inorder
Threaded Binary Trees
Inorder traversal of a threaded binary tree
void tinorder(threaded_pointer tree){
/* traverse the threaded binary tree inorder */
threaded_pointer temp = tree;
for (;;) { output: H D I B E A F C G
temp = insucc(temp);
if (temp==tree)
break;
printf(“%3c”,temp->data); tree
}
}

Time Complexity: O(n)


Threaded Binary Trees
Inserting A Node Into A Threaded Binary Tree
Insert child as the right child of node parent
1. change parent->right_thread to FALSE
2. set child->left_thread and child->right_thread to TRUE
3. set child->left_child to point to parent
4. set child->right_child to parent->right_child
5. change parent->right_child to point to child
Threaded Binary Trees
Right insertion in a threaded binary tree
void insert_right(thread_pointer parent, threaded_pointer child){
/* insert child as the right child of parent in a threaded binary tree */
threaded_pointer temp;
child->right_child = parent->right_child; root
child->right_thread = parent->right_thread;
child->left_child = parent; A parent
child->left_thread = TRUE;
parent->right_child = child; B
parent->right_thread = FALSE;
If(!child->right_thread){ C X child
temp = insucc(child);
temp->left_child = child; temp
A parent
}
} B child
X
C
D
First Case
Second Case
E F
successor
Binary Search Trees
Searching a
binary search
tree

O(h)
Binary Search Tree
The value at any node,
• Greater than every value in left subtree
• Smaller than every value in right subtree
– Example
• Y>X

• Y<Z Y

X Z
Binary Search Tree
• Values in left sub tree less than parent
• Values in right sub tree greater than parent
• Fast searches in a Binary Search tree, maximum of log
n comparisons
31

21 40

10 22 35 42
Binary Search Trees
• Examples 5
10 10
2 45
5 30 5 45
30
2 25 45 2 25 30
10

25
Binary search Not a binary
trees search tree
Example Binary Searches
• search (root, 25 )
10 5
10 < 25, right 5 < 25, right
5 30 30 > 25, left 2 45 45 > 25, left
25 = 25, found 30 > 25, left
2 25 45 30
10 < 25, right
10 25 = 25, found

25
Algorithm for Binary Search Tree
⚫ A) compare ITEM with the root node N of the tree
⚫ i) if ITEM<N, proceed to the left child of N.
⚫ ii) if ITEM>N, proceed to the right child of N.
⚫ B) repeat step (A) until one of the following occurs
⚫ i) we meet a node N such that ITEM=N, i.e. search is
successful.
⚫ ii) we meet an empty sub tree, i.e. the search is
unsuccessful.
Binary Tree Implementation
typedef struct node
{
int data;
struct node *lc,*rc;
};
Iterative Search of Binary Search Tree
search()
{
while (n != NULL)
{
if (n->data == item) // Found it
return n;
if (n->data > item) // In left subtree
n = n->lc;
else // In right subtree
n = n->rc;
}
return null;
}
Recursive Search of Binary Search Tree
Search(node *n, info)
{
if (n == NULL) // Not found
return( n );
else if (n->data == item) // Found it
return( n );
else if (n->data > item) // In left subtree
return search( n->left, item );
else // In right subtree
return search( n->right, item );
}
Binary Search Trees
Inserting into a binary search tree

An empty tree
Insertion in a Binary Search Tree
• Algorithm
1. Perform search for value X
2. Search will end at node Y (if X not in tree)
3. If X < Y, insert new leaf X as new left subtree
for Y
4. If X > Y, insert new leaf X as new right subtree
for Y
Insertion in a Binary Search Tree
• Insert ( 20 )
10 10 < 20, right
30 > 20, left
5 30
25 > 20, left
2 25 45 Insert 20 on left

20
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11

40
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11
40

60
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11
40

60

50
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11
40

33 60

50
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11
40

33 60

50

55
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11
40

33 60

11 50

55
Deletion in Binary Tree
• Algorithm
1. Perform search for value X
2. If X is a leaf, delete X
3. Else //we must delete internal node
a) Replace with largest value Y on left subtree
OR smallest value Z on right subtree
b) Delete replacement value (Y or Z) from subtree
Note :-
– Deletions may unbalance tree
Example Deletion (Leaf)
• Delete ( 25 )
10 10
10 < 25, right
5 30 30 > 25, left 5 30
25 = 25, delete
2 25 45 2 45
Example Deletion (Internal Node)

• Delete ( 10 )
10 5 5

5 30 5 30 2 30

2 25 45 2 25 45 2 25 45

Replacing 10 Replacing 5 Deleting leaf


with largest with largest
value in left value in left
subtree subtree
Example Deletion (Internal Node)

• Delete ( 10 )
10 25 25

5 30 5 30 5 30

2 25 45 2 25 45 2 45

Replacing 10 Deleting leaf Resulting tree


with smallest
value in right
subtree
Binary Search Trees
Height of a binary search tree
The height of a binary search tree with n elements can
become as large as n.
It can be shown that when insertions and deletions are made
at random, the height of the binary search tree is O(log2n) on
the average.
Search trees with a worst-case height of O(log2n) are called
balance search trees
Binary Search Trees
Time Complexity
Searching, insertion, removal
O(h), where h is the height of the tree
Worst case - skewed binary tree
O(n), where n is the # of internal nodes
Prevent worst case
rebalancing scheme
AVL, 2-3, and Red-black tree
Binary Search Properties
• Time of search
– Proportional to height of tree
– Balanced binary tree
• O( log(n) ) time
– Degenerate tree
• O( n ) time
• Like searching linked list / unsorted array
AVL Tree
⚫ AVL trees are height-balanced binary search trees
⚫ Balance factor of a node=
height(left sub tree) - height(right sub tree)
⚫ An AVL tree has balance factor calculated at every node
⚫ For every node, heights of left and right sub tree can
differ by no more than 1
⚫ Store current heights in each node
AVL Tree
⚫ A binary tree in which the difference of height of the
right and left subtree of any node is less than or equal
to 1 is known as AVL Tree.
⚫ Height of left subtree – height of right subtree
can be either -1,0,1
AVL Tree

0 0 0

0
AVL Tree
1

-1 0
3 2
0 1 0 0

Balanced as LST-RST=1
Insertion in AVL Tree

Case 1: the node was either left heavy or right heavy


and has become balanced
Insertion in AVL Tree

Case 2: the node was balanced and has now become


left or right heavy
Insertion in AVL Tree

2
3

Case 3: the node was heavy and the new node has been inserted in
the heavy sub tree thus creating an unbalanced sub tree
Rebalancing
• When the tree structure changes (e.g., insertion or
deletion), we need to transform the tree to restore the
AVL tree property.
• This is done using single rotations or double rotations.
Rotations
• single rotations

e.g. Single Rotation


y
x
x
y C
A C
B
B
A Before Rotation After Rotation
Rotations
• Since an insertion/deletion involves
adding/deleting a single node, this can
only increase/decrease the height of some
subtree by 1
• Thus, if the AVL tree property is violated
at a node x, it means that the heights of
left(x) and right(x) differ by exactly 2.
• Rotations will be applied to x to restore
the AVL tree property.
Single Rotation
The new item is inserted in the subtree A.
The AVL-property is violated at x
height of left(x) is h+2
height of right(x) is h.
Single Rotation
The new item is inserted in the subtree C.
The AVL-property is violated at x.

Single rotation takes O(1) time.


Insertion takes O(log N) time.
Double Rotation
The new key is inserted in the subtree B1 or B2.
The AVL-property is violated at x.
x-y-z forms a zig-zag shape

also called left-right rotate


Double Rotation
The new key is inserted in the subtree B1 or B2.
The AVL-property is violated at x.

also called right-left rotate


Example
Insert 3,2,1,4,5,6,7

3
Example
Insert 3,2,1,4,5,6,7
3

2
Example
Insert 3,2,1,4,5,6,7
3

1
Example
Insert 3,2,1,4,5,6,7
Single rotation

1
Example
Insert 3,2,1,4,5,6,7
2

1
3
Example
Insert 3,2,1,4,5,6,7
2

1
3

4
Example
Insert 3,2,1,4,5,6,7
2

1
3

5
Example
Insert 3,2,1,4,5,6,7
2
Single rotation
1
3

5
Example
Insert 3,2,1,4,5,6,7
2

1
4

3 5
Example
Insert 3,2,1,4,5,6,7
2

1
4

3 5

6
Example
Insert 3,2,1,4,5,6,7
Single rotation
2

1
4

3 5

6
Example
Insert 3,2,1,4,5,6,7
4

2
5

1 3 6
Example
Insert 3,2,1,4,5,6,7
4

2
5

1 3 6

7
Example
Insert 3,2,1,4,5,6,7
4

Single rotation
2
5

1 3 6

7
Example
Insert 3,2,1,4,5,6,7
4

2
6

1 3 5 7
AVL Insertion: Outside Case

Consider a valid
AVL subtree
j

k h

h
h
Z
X Y
AVL Insertion: Outside Case

j Inserting into X
destroys the AVL
property at node j
k h

h+1 h Z
Y
X
AVL Insertion: Outside Case

j Do a “right rotation”

k h

h+1 h Z
Y
X
Single right rotation

j Do a “right rotation”

k h

h+1 h Z
Y
X
Outside Case Completed

“Right rotation” done!


k (“Left rotation” is mirror
symmetric)

h+1
j
h h

X Y Z
AVL property has been restored!
AVL Insertion: Inside Case

Consider a valid
AVL subtree
j

k h

h h Z
X Y
AVL Insertion: Inside Case

Inserting into Y
destroys the
j Does “right rotation”
restore balance?
AVL property
at node j
k h

h h+1 Z
X
Y
AVL Insertion: Inside Case

k “Right rotation”
does not restore
balance… now k is
h j out of balance

X h+1
h

Z
Y
AVL Insertion: Inside Case

Consider the structure


of subtree Y…
j
k h

h h+1 Z
X
Y
AVL Insertion: Inside Case

Y = node i and
subtrees V and W
j
k h

h
i h+1 Z
X h or h-1

V W
AVL Insertion: Inside Case

j We will do a left-right
“double rotation” . . .

k
i Z
X
V W
Double rotation : first rotation

j left rotation complete

i
k Z
W
X V
Double rotation : second rotation

j Now do a right rotation

i
k Z
W
X V
Double rotation : second rotation

right rotation complete

Balance has been


i restored

k j
h h
h or h-1

X V W Z
Comparative analysis of AVL ,Red black, and
Splay Tree
Performance of Binary Search Tree (BST) is proportional to
its height O(h).

To achieve best performance, it is important to balance the


tree.

AVL tree, Red-Black tree and Splash tree are popular self-
balacing BSTs.

Like AVL tree, Splay tree and Red-Black tree are self-
balancing trees which provide O(Log n) search
performance.
Comparative analysis of AVL ,Red black, and
Splay Tree
•The AVL tree is another structure supporting O(log n) search, insertion, and
removal.

•It is more rigidly balanced than red–black trees, leading to slower insertion
and removal but faster retrieval.

•This makes it attractive for data structures that may be built once and loaded
without reconstruction, such as language dictionaries.

• The competitor of avl tree is Red–black tree. The worst case height of avl tree
is ~1.44 log(n), of red black tree is 2 log(n).

• But as insertion and deletion in avl tree is costly(more rotation than red
black tree) than red black,avl tree is not used much.
performance.
Comparative analysis of AVL ,Red black, and
Splay Tree
•Red-Black tree is preferred over AVL trees when there is
high frequency of insert/delete operations compared to
search as AVL tree balancing (rotation) is expensive.
•Red-black tree balances itself on insert and delete
operations satisfying the following conditions.
•Each node is either red or black. Usually color information
is stored in a bit in the node.
a) Root and leaf nodes are black.
b) No two red nodes to be adjacent, meaning, a red node
cannot have a parent or children which are red.
c) Every path from root to leaf nodes have same number of
black nodes.
Comparative analysis of AVL ,Red black, and
Splay Tree
•Splay tree provides performance better than O(log n)
by optimizing the placement of nodes.

• It makes the recently accessed nodes in the top of the


tree and hence providing better performance.

•It’s suitable for cases where there are large number of


nodes but only few of them are accessed frequently.
B-Tree
B-tree is a fairly well-balanced tree.

All leaves are on the bottom level.


All internal nodes (except perhaps the root node) have
at least cell(m / 2) (nonempty) children.
The root node can have as few as 2 children if it is an
internal node, and can obviously have no children if the
root node is a leaf (that is, the whole tree consists only
of the root node).
Each leaf node (other than the root node if it is a leaf)
must
contain at least ceil(m / 2) - 1 keys.
Let's work our way through an example similar to that given
by Kruse. Insert the following letters into what is originally
an empty B-tree of order 5:

C N G A H E K Q M F W L T Z D P R X Y S

Order 5 means that a node can have a maximum of 5


children and 4 keys. All nodes other than the root must
have a minimum of 2 keys. The first 4 letters get inserted
into the same node, resulting in this picture:
When we try to insert the H, we find no room in this node, so we split
it into 2 nodes, moving the median item G up into a new root node.
Note that in practice we just leave the A and C in the current node and
place the H and N into a new node to the right of the old one.

Inserting E, K, and Q proceeds without requiring any splits:

H E K Q M F W LT Z D P R XY S
Inserting M requires a split. Note that M happens to be the
median key and so is moved up into the parent node.

The letters F, W, L, and T are then added without needing any


split.

M F W LT Z D P R XY S
When Z is added, the rightmost leaf must be split. The median item T is moved
up into the parent node. Note that by moving up the median key, the tree is kept
fairly balanced, with 2 keys in each of the resulting nodes.

The insertion of D causes the leftmost leaf to be split. D happens to be the median
key and so is the one moved up into the parent node. The letters P, R, X, and Y are
then added without any need of splitting:

Z D P R XY S
Finally, when S is added, the node with N, P, Q, and R splits, sending the
median Q up to the parent. However, the parent node is full, so it splits,
sending the median M up to form a new root node. Note how the 3
pointers from the old parent node stay in the revised node that contains D
and G.
THANK YOU

You might also like