Sei sulla pagina 1di 47

Tree and Tree terminology:

A Tree is a non-linear data structure which organizes data in a hierarchical structure (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 such graph is called
as a Tree.
Tree Terminology :
The important terms related to tree data structure are ..

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.
Ex:

Here, node A is the only root node.


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.
Ex:

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.
Ex:

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
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.
Ex:

Here,
Nodes B and C are the children of node A
Nodes D, E and F are the children of node B and Likewise.
Siblings:
Nodes which belong to the same parent are called as siblings.
In other words, nodes with the same parent are sibling nodes.
Ex:

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
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.
Ex:

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
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.
Ex:

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

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.
Ex:

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


nodes.
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.
Ex:

Height:
Total number of Edges that lies on the longest (downward) path from any node to a leaf node is
called as Height of that Node.
Height of a tree is the height of root node.
Height of all leaf nodes will be 0.
Ex:
In the Above Diagram ,
Height of node A = 3
Height of node B = 2
Height of node C = 2
Height of node E = 1
Height of node G = 1
Height of all Leaf Nodes F,D,H,I,J,K = 0

Depth:
Total number of edges from root node to a particular node is called as depth of that node.
OR
Depth of a tree is the total number of edges from node to a root node in the longest (upward) path.
Depth of the root node will always be 0
The terms “level” and “depth” are used interchangeably.
Ex:

Here,
Depth of node A = 0 (root node) 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
Subtree:
In a tree, each child from a node forms a subtree recursively.
Every child node forms a subtree on its parent node.
Ex:

Forest:
A forest is a set of disjoint trees.
Ex:

Advantages of trees:
 Trees reflect structural relationships in the data
 Trees are used to represent hierarchies
 Trees provide an efficient insertion and searching
 Trees are very flexible data, allowing to move sub trees around with minimum effort
Application of Trees:
One reason to use trees might be because you want to store information that naturally forms a
hierarchy. For example, the File System on a computer:
File System
/ <-- root
/ \
... home
/ \
upgrade course
/ / | \
... cs11 cs12 cs13

What is a Binary Tree and state its types?


Binary Tree is a special type of generic tree in which, each node can have at most two children.
OR
A binary tree is a tree data structure in which each node has at most two children, which are referred
to as the left child and the right child.
A binary tree is made of nodes, where each node contains a "Left" reference, a "Right" reference,
and a data element.

Left_Child Data Right_Child

In the above Binary Tree each node contains Left_Child , Data and Right_Child .
Node 1 is the root and its Left_Child is pointing to node 2 and Right_Child to node 3.
Node 2 is the child of node 1 and its Left_Child is pointing to node 5 and Right_Child to node 4.
Node 4 is a leaf node because it has no children.
Node 5 is the child of node 2 and its Left_Child is pointing to node 6 and Right_Child to node 7.
Both Node 6 and 7 are leaf nodes.
Node 3 is the child of node 1 and its Left_Child and Right_Child are pointing to nothing thus it is a
leaf node.
Types of Binary Tree: There are three different types of Binary Trees :

1. Full Binary Tree:


A Binary Tree is full if every node has 0 or 2 children. We can also say a full binary tree
is a binary tree in which all nodes except leaves have two children. It is also known as proper
binary tree or 2-tree.
In a Full Binary, number of leaf nodes is number of internal nodes plus 1
L=I+1
Where L = Number of leaf nodes, I = Number of internal nodes
2. Complete Binary Tree:
A complete binary tree is a binary tree in which every level, except possibly the last, is
completely filled, and all nodes are as far left as possible.
3. Perfect Binary Tree:
A Binary tree is Perfect Binary Tree in which all internal nodes have two children and all
leaves are at the same level.A Perfect Binary Tree of height h (where height is the number of nodes
on the path from the root to leaf) has 2h – 1 node.Example of a Perfect binary tree is ancestors in
the family. Keep a person at root, parents as children, and parents of parents as their children.

Binary Tree Representation


We can represent binary tree in two ways:
1. Linked Representation: In this representation, the binary tree is stored in the memory, in the form
of a linked list where the number of nodes are stored at non-contiguous memory locations and
linked together by inheriting parent child relationship like a tree.
2. Sequential Representation: In this representation, an array is used to store the tree elements. Size
of the array will be equal to the number of nodes present in the tree. The root node of the tree will
be present at the 1st index of the array.
Disadvantages of Sequential Representation is:

 Adding and deleting a node is a tough job here


 Memory may get wasted
 Height of the tree should be known in prior
Sequential Represent is not used because of its disadvantages , we will learn how binary search tree
is implemented in Linked Representation .

Explain Binary tree Traversals with an example?


A traversal is a process that visits all the nodes in the tree. Since a tree is a nonlinear data
structure, there is no unique traversal. We will consider several traversal algorithms with we group
in the following two kinds
 Breadth-first traversal
 Depth-first traversal

Breadth First Traversal


There is only one Breadth-first traversal:
1. Level order traversal:
This traversal visits nodes by levels from top to bottom and from left to right.
Breadth First Traversal is a traversing way where child at same levels are read first before visiting
their parent.
To traverse a binary tree in Level order, following operations are carried-out
(a) Visit the nodes of tree Level by Level (i.e from left to right, level by level).
(b) Here every Node of same Level is visited first before going to a lower level.
Therefore, the Level order traversal of the below sample tree will outputs:
45 25 75 15 35
For reading a Tree Level by Level, we require Queue to store the Nodes.

Algorithm:
1. Put a Root Node in a Queue.
2. Iterate till the Queue is not Empty.
3. While iterating, take one element from Queue say 45 in our example, print it and put children's
of 45 in queue.
4. Repeat steps till Queue is not empty.
Ex2:

Level Order - 8, 5, 4, 9, 7, 11, 1, 12, 3, 2


Depth-first traversal:
There are three different types of depth-first traversals:
1. PreOrder traversal
2. InOrder traversal
3. PostOrder traversal
We will try different traversal of Depth first on this tree

1.Pre Order Traversal - visit the parent first and then left and right children;
Algorithm: PreOrder(tree)
 Check if(root!=NULL) then
 Visit the root node and print data of node.
 Traverse the left subtree, i.e., call PreOrder(left-subtree)
 Traverse the right subtree, i.e., call PreOrder(right-subtree)
PreOrder traversal of the above tree- 8, 5, 9, 7, 1, 12, 2, 4, 11, 3
2.InOrder Traversal - visit the left child, then the parent and the right child;
Algorithm: InOrder(tree)
 Check if (root != NULL) then
 Traverse the left subtree, i.e., call InOrder(left-subtree)
 Visit the root node and print data of node.
 Traverse the right subtree, i.e., call InOrder(right-subtree)
InOrder - 9, 5, 1, 7, 2, 12, 8, 4, 3, 11
3.PostOrder traversal - visit left child, then the right child and then the parent;
Algorithm: PostOrder(tree)
 Check if(root!=NULL) then
 Traverse the left subtree, i.e., call PostOrder(left-subtree)
 Traverse the right subtree, i.e., call PostOrder(right-subtree)
 Visit the root and print data of node.
PostOrder - 9, 1, 2, 12, 7, 5, 3, 11, 4, 8
What is Binary Search Tree (BST)?
Binary search tree is a data structure that quickly allows us to maintain a sorted list of numbers.
It is called a binary tree because each tree node has maximum of two children.
A binary search tree is a useful data structure for fast addition and removal of data.
It is called a search tree because it can be used to search for the presence of a number
in O(log(n)) time.
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 parent’s key.
 The right subtree of a node contains only nodes with keys greater than the parent’s key.
 The left and right subtree each must be a binary search tree.

A Binary search tree is shown in the above figure. As the constraint applied on the BST, we can see
that the root node 8 doesn't contain any value greater than or equal to 8 in its left sub-tree and it also
doesn't contain any value less than 8 in its right sub-tree.

Binary Search Tree

Time complexities in big O notation

Average Worst case

Space O(n) O(n)

Search O(log n) O(n)

Insert O(log n) O(n)

Delete O(log n) O(n)


Advantages of using Binary Search Tree:
 The binary search tree is considered as efficient data structure in compare to arrays and
linked lists. In searching process, it removes half sub-tree at every step. Searching for an
element in a binary search tree takes O(logn) time. In worst case, the time it takes to search
an element is O(n).
 It also speeds up the insertion and deletion operations as compare to that in array and linked
list.
 We have an ordering of keys stored in the tree. Any time we need to traverse in increasing
(or decreasing) order of keys, we just need to do the in-order (and reverse in-order) traversal
on the tree.
 BST can also be used in the design of memory allocators to speed up the search of free
blocks (chunks of memory), and to implement best fit algorithms where we are interested in
finding the smallest free chunk with size greater than or equal to size specified in allocation
request.
Disadvantages of using BST:
 The main disadvantage is that we should always implement a balanced binary search tree -
AVL tree, Red-Black tree, Splay tree. Otherwise the cost of operations may not be
logarithmic and degenerate into a linear search on an array.
 BST uses more space as every element in binary search tree should have left and right links
to the children.

Explain the Implementation of a BST with an example:


A BST can be implemented using linked lists i.e. using linked representation of binary trees.
For a BST the link contains info, left and right fields, whereas a list node requires only info and
next fields.
Create a self-referential structure or structure “Node”
Structure of BST:
struct Node
{
int data;
struct Node *right_child;
struct Node *left_child;
};
Here,
 data - data you want to store in binary tree.
 *right_child - pointer to the right subtree
 *left_child -pointer to the left subtree.
The *right_child / *left_child will store location of next node if exists otherwise NULL.
Node 6 is the root and its Left_Child is pointing to node 4 and Right_Child to node 8.
Node 4 is the child of node 6 and its Left_Child is pointing to node 2 and Right_Child to node 5.
Node 2 is the child of node 4 and its Left_Child is pointing to node 1 and Right_Child to node 3.
Node 5,1,3 are leaf nodes because it has no children.
Node 8 is the child of node 6 and its Left_Child is pointing to node 7 and Right_Child to node 13.
Node 9 is the child of node 7 and is a leaf node.

Here, 4,2,5,1,3 are < 6 since they are left of the binary search tree and 8,7,13,9 are >= 6 since they
are right of the binary search tree.

Ex: Create the binary search tree using the following data elements:-43, 10, 79, 90, 12, 54, 11, 9, 50
 Insert 43 into the tree as the root of the tree.
 Read the next element, if it is lesser than the root node element, insert it as the root of the
left sub-tree.
 Otherwise, insert it as the root of the right of the right sub-tree.
 The process of creating BST by above elements is shown in the image below.
Comparision between Binary Tree and Binary Search Tree:

Binary Tree Binary Search Tree


Definition Binary Tree is a specialized form of Binary Search Tree is a type of binary
tree which represents hierarchical tree which keeps the keys in a sorted
data in a tree structure. order for fast lookup.

Structure Each node must have at the most The value of the nodes in the left
two child nodes with each node subtree are less than or equal to the
being connected from exactly one value of the root node, and the nodes
other node by a directed edge. to the right subtree have values
greater than or equal to the value of
the root node.

Order There is no relative order to how It follows a definitive order to how the
the nodes should be organized nodes should be organized in a tree.
It’s basically a hierarchical data It’s a variant of the binary tree in which
structure that is a collection of the nodes are arranged in a relative
elements called nodes order.
Operation It is mainly used for insertion, deletion, It is used for fast and efficient lookup of
and searching of elements. data and information in a tree structure.

Types Different types of binary trees are the T-trees, AVL trees, Splay trees, Tango
“Full Binary Tree”, “Complete Binary trees, Red-Black trees etc
Tree”, “Perfect Binary Tree”, and
“Extended Binary Tree”
Operations on BST:
Operations on Binary Search Tree are Search ,Insertion ,Deletion .
Searching Operation in BST :
Searching - finding or locating some specific element or node within a data structure.
However, searching for some specific node in binary search tree is pretty easy due to the fact that,
element in BST are stored in a particular order.
Searching a binary search tree for a specific value is of two types:
 Recursive
 Iterative process.
This explanation covers a recursive method,we begin by examining the root node.
If the tree is null, the value we are searching for does not exist in the tree.
Otherwise, if the value equals the root, the search is successful. If the value is less than the root,
search the left subtree.
Similarly, if it is greater than the root, search the right subtree.
This process is repeated until the value is found or the indicated subtree is null. If the searched
value is not found before a null subtree is reached, then the item must not be present in the tree.
This operation requires O (log n) time in the average case, but needs O(n) time in the worst case,
when the unbalanced tree resembles a linked list (degenerate tree).

Here is the Search Algorithm:


Search (ROOT, ITEM)
Step 1: If root→data=key or root=NULL
Return root
Step 2: Else if key>root→data
Return search(root→right_child,key)
Step 3: Else
Return search(root→left_child,key)

For Ex: Consider the following binary tree and find 60 in the BST.
Compare the 60 with the root of the tree i.e 50.
If the key is matched then return the location of the node.
Otherwise check if 60 is less than the element present on root(50), if so then move to the left sub-
tree.
But 60 > 50 thus move to the right sub-tree.
Now root is 75. 60 < 75 thus move to the left sub-tree.
If 60 = 60 , return root.

Insertion Operation in BST:


Insertion begins as a search would begin; if the root is not equal to the value, we search the left or
right subtrees as before. Eventually, we will reach an external node and add the value as its right or
left child, depending on the node's value. In other words, we examine the root and recursively insert
the new node to the left subtree if the new value is less than the root, or the right subtree if the new
value is greater than or equal to the root.
Insert function is used to add a new element in a binary search tree at appropriate location. Insert
function is to be designed in such a way that, it must not violate the property of binary search tree at
each value.
The algorithm for insertion is similar to search.
Here, is the Insertion algorithm:
Insert(root , key)
Step 1: if root = NULL then
Create a temporary node ; root=temp
Step 2: Else if key > root→data then root→right_child = insert(root→right_child,key)
Step 3: Else root→left_child = insert(root→left_child,key)
Step 4: Finally return root
For Ex: consider the following binary tree and insert 95 in the BST.
Allocate the memory for new node.
Set the data part to the value and set the left and right pointer of node, point to NULL.
As 95 > 50, move to right sub-tree.
Now root is 75; 95 > 75 move to right sub-tree.
Now root is 85; 95 >85 as right_child of 85 is NULL point it to temp node in which 95 is present.
Return root and 95 is inserted in BST.

Deletion operation in BST:


Delete function is used to delete the specified node from a binary search tree. However, we must
delete a node from a binary search tree in such a way, that the property of binary search tree doesn't
violate. There are three situations of deleting a node from binary search tree.
There are three possible cases to consider:
 Deleting a leaf node
 Deleting a node with one child.
 Deleting a node with two children.
The deletion algorithm is similar to Search.
If the node to be deleted is a leaf node:
It is the simplest case, in this case, replace the leaf node with the NULL and free the allocated
space.
Algorithm:
Step 1: if root→ left_child and right_child are both equal to NULL(&&)
Step 2: free the memory of the root and return NULL
In the following BST, we are deleting the node 85, since the node is a leaf node, therefore the node
will be replaced with NULL and allocated space will be freed.

If the node to be deleted has only one child:


In this case, replace the node with its child and delete the child node, the node’s child is set as the
child of the node’s parent. In other words, replace the node with its child. Now, if the node is the
left child of its parent, the node’s child becomes the left child of the node’s parent.
Correspondingly, if the node is the right child of its parent, the node’s child becomes the right child
of the node’s parent . Simply replace it with the NULL and free the allocated space.
Algorithm:
Step 1: check if root→ right_child or root→ left_child are equal to NULL
Step 2: Create a temporary node
Step 3: if root→ left_child = NULL then temp <- root→right_child
Similarly, if root→right_child =NULL then temp <- root→left_child
Step 4: free root and return temp.
In the following BST, the node 12 is to be deleted. It has only one child. The node will be replaced
with its child node and the replaced node 12 (which is now leaf node) will simply be deleted.
The node to be deleted has two children:
It is a bit complex case compare to other two cases. However, the node which is to be deleted, is
replaced with its in-order successor or predecessor recursively until the node value (to be deleted) is
placed on the leaf of the tree. After the procedure, replace the node with NULL and free the
allocated space.

InOrder Predecessor and InOrder Successor:

We can Use any one either Inorder successor or the predecessor.


Algorithm:
Step 1: create a temp node and store the InOrder successor [the node] of the key to be deleted in
temp .
Step 2: root→data = temp→data
Step 3: root→right_child = delete (root→right_child , temp→data) // this refers to the InOrder
Successor in the Binary Search Tree.
Step 4: return root.
In the following BST, the node 50 is to be deleted which is the root node of the tree. The in-order
traversal of the tree given below.
6, 25, 30, 50, 52, 60, 70, 75.
replace 50 with its in-order successor 52. Now, 50 will be moved to the leaf of the tree, which will
simply be deleted.
AVL Tree
AVL tree is a binary search tree in which the difference of heights of left and right subtrees of any
node is less than or equal to one. The technique of balancing the height of binary trees was
developed by Adelson, Velskii, and Landi and hence given the short form as AVL tree or Balanced
Binary Tree.

If height exceeds 1 level then rebalancing occurs.

OR

AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights
of left and right subtrees cannot be more than one for all nodes

i.e., balancing factor for each node is either 0 or 1 or -1.

Below is a balanced AVL tree.

Below is a ImBalanced AVL tree.

The AVL Tree has a bad cost in inserting and removing data because it has to self sort itself each
and every time. It has a wonderful searching capacity with O(log(n)) running time guarranteed
making the AVL Tree so popular.
It is best to implement the operations of AVL Trees it under recursion because the tree should be
rotating from the leaves balancing itself up to the general root.
Why AVL Trees ? [Advantages of AVL tree]

Most of the BST operations (e.g., search, max, min, insert, delete.. etc) take O(h) time where h is the
height of the BST. The cost of these operations may become O(h) for a skewed Binary tree. If we
make sure that height of the tree remains O(Log h) after every insertion and deletion, then we can
guarantee an upper bound of O(Log h) for all these operations. The height of an AVL tree is always
O(Log h) where h is the number of nodes in the tree.

A skewed tree is a tree where each node has only one child node or none. This type of BST is similar
to a linked list.
AVL Trees are self- balancing Binary Search Trees (BSTs). A normal BST may be skewed to either
side which will result in a much greater effort to search for a key (the order will be much more
than O( log2n) O(log2n) ) and sometimes equal O( n O(n) ) at times giving a worst case result which
is the same effort spent in sequential searching. This makes BSTs useless as a practically efficient
Data Structure.

Height of an AVL tree[Balance Factor]

Balance Factor: It is defined as the difference between height of left subtree and height of right
subtree.

Balance Factor (k) = height (left(k)) - height (right(k))

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.

An AVL tree is given in the following figure. We can see that, balance factor associated with each
node is in between -1 and +1.
Therefore, it is an example of AVL tree.

Different Time Complexities of Operation of AVL Trees are:


AVL tree
Type Tree
Invented 1962
Invented by G.M.Adelson-Velskiiand
E.M.Landis
Time complexity in big O notation
Average Worst case
Space O(n) O(n)
Search O(log n) O(log n)
Insert O(log n) O(log n)
Delete O(log n) O(log n)

AVL Tree Operations-


Like BST Operations, commonly performed operations on AVL tree are-
 Search Operation
 Insertion Operation
 Deletion Operation
After performing any operation on AVL tree, the balance factor of each node is checked.

There are following two cases possible with the balance factor:
Case-01:
After the operation, the balance factor of each node is either 0 or 1 or -1.
In this case, the AVL tree is considered to be balanced.
The operation is concluded.
Case-02:
After the operation, the balance factor of at least one node is not 0 or 1 or -1.
In this case, the AVL tree is considered to be imbalanced.
Rotations are then performed to balance the imbalanced AVL tree.

AVL Tree Rotations-


Rotation is the process of moving the nodes to make tree balanced.
Kinds of Rotations:
There are 4 kinds of rotations possible in AVL Trees-

Cases Of Imbalance And Their Balancing Using Rotation Operations-


Case-01: Single Left Rotation (LL Rotation)
Case-02: Single Right Rotation (RR Rotation)

Case-03: Left Right Rotation (LR Rotation)

Case-04: Right Left Rotation (RL Rotation)


AVL Tree Insertion

Insertion in AVL tree is performed in the same way as it is performed in a binary search tree. The
new node is added into AVL tree as the leaf node. However, it may lead to violation in the AVL tree
property and therefore the tree may need balancing.

To insert an element in the AVL tree, follow the following steps-


Insert the element in the AVL tree in the same way the insertion is performed in BST.
After insertion, check the balance factor of each node of the resulting 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...
Algorithm:
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.

Rules To Remember while inserting element in AVL tree:


Rule-01:
 After inserting an element in the existing AVL tree,
 Balance factor of only those nodes will be affected that lies on the path from the newly
inserted node to the root node.
Rule-02:
 To check whether the AVL tree is still balanced or not after the insertion,
 There is no need to check the balance factor of every node.
 Check the balance factor of only those nodes that lies on the path from the newly inserted
node to the root node.
Rule-03:
 After inserting an element in the AVL tree,
 If tree becomes imbalanced, then there exists one particular node in the tree by balancing
which the entire tree becomes balanced automatically.
 To re balance the tree, balance that particular node.
 To find that particular node,
 Traverse the path from the newly inserted node to the root node.
 Check the balance factor of each node that is encountered while traversing the path.
 The first encountered imbalanced node will be the node that needs to be balanced.
 To balance that node, Count three nodes in the direction of leaf node.
 Then, use the concept of AVL tree rotations to re balance the tree.
Problem-[example: 1]
Q. Construct an AVL tree by inserting the following elements in the given order.
63, 9, 19, 27, 18, 108, 99, 81
The process of constructing an AVL tree from the given set of elements is shown in the following
figure.
At each step, we must calculate the balance factor for every node, if it is found to be more than 2 or
less than -2, then we need a rotation to rebalance the tree. The type of rotation will be estimated by
the location of the inserted element with respect to the critical node.
All the elements are inserted in order to maintain the order of binary search tree.
Observe the below diagram and go for the steps mentioned.

STEPS FOR INSERTION:


Step-01: Insert 63
Step-02: Insert 9
 As 9 < 63, so insert 9 in 63’s left sub tree.
Step-03: Insert 19
 As 19 < 63, so insert 19 in 63’s left sub tree.
 As 9 > 9, so insert 19 in 9’s right sub tree.
Step-04: check balancing as tree is not balanced
To balance the tree, As the tree is imbalanced and by seeing the tree we can perform LR rotation to
balance the tree. Now the tree is balanced.
Step-05: Insert 27
 As 27 > 19, so insert 27 in 19's right sub tree.
 As 27 < 63, so insert 27 in 63's left sub tree.
Step-06: Insert 18
 As 18< 19, so insert 18 in 19's left sub tree
 As 18 > 9, so insert 18 in 9's right sub tree.
Step-07: Insert 108
 As 108 > 19, so insert 108 in 19's right sub tree
 As 108 > 63, so insert 108 in 63's right sub tree
Step-08: Insert 99
 As 99 > 19, so insert 99 in 19's right sub tree
 As 99 > 63, so insert 99 in 63's right sub tree
 As 99 < 108, so insert 99 in 108's left sub tree
Step-09: Insert 81
 As 81 > 19, so insert 81 in 19's right sub tree
 As 81 > 63, so insert 81 in 63's right sub tree
 As 81 < 108, so insert 81 in 108's left sub tree
 As 81 < 99, so insert 81 in 99's left sub tree
To balance the tree,
As the tree is imbalanced and by seeing the tree we can perform LL rotation to balance the tree.
Now the tree is balanced.
Step-10: Balanced
This is the final balanced AVL tree after inserting all the given elements.
Problem-[example: 2]
Q. Insert an element to the below AVL tree.
Insert 8
Steps :
 As 8<50, so insert 8 in 50's left sub tree
 As 8<20, so insert 8 in 20's left sub tree
 As 8<10, so insert 8 in 10's left sub tree
As the tree is imbalanced and by seeing the tree we can perform RR rotation to balance the tree.
Now the tree is balanced.
Problem-[example: 3]
Q. Insert an element to the below AVL tree.
Insert 15
Steps:
 As 15>5, so insert 15 in 5's right sub tree
 As 15>7, so insert 15 in 7's right sub tree
 As 15>9, so insert 15 in 9's right sub tree
 As 15<16, so insert 15 in 16's left sub tree
 As 1<20, so insert 8 in 20's left sub tree
 As 8<10, so insert 8 in 10's left sub tree
As the tree is imbalanced and by seeing the tree we can perform RL rotation to balance the tree.
Now the tree is balanced.
AVL Tree Deletion:
Deleting a node from an AVL tree is similar to that in a binary search tree. Deletion may disturb the
balance factor of an AVL tree and therefore the tree needs to be rebalanced in order to maintain the
AVL tree properties. For this purpose, we need to perform rotations.
Algorithm:
Step 1: Firstly, find that node where k is stored{k=key}
Step 2: Secondly delete those contents of the node (Suppose the node is x)
Step 3: Deleting a node in an AVL tree can be reduced by deleting a leaf.
There are three possible cases:
1. When x has no children then, delete x
2. When x has one child, let ‘x' becomes the child of x.
Notice: x cannot have a child, since subtrees of T can differ in height by at most one ,then
replace the contents of x with the contents of x , then delete x (a leaf)
3. When x has two children, then find x's successor z (which has no left child) then replace x's
contents with z's contents, and delete z .
In all of the three cases, you will end up removing a leaf and we need to check for balance
of the AVL Tree.
Ex:
Delete the node 30 from the following AVL tree

AVL Tree Searching:


Searching a node from an AVL tree is similar to that in a binary search tree.
Algorithm:
Step 1: First compare your key to be searched with the root
If it is equal to root then key is found.
Step 2: If key < root , move to left subtree and again compare elements and repeat same.
Step 3: If key > root , move to right subtree and again compare elements and repeat same.
Red-Black Tree:
Red-Black Tree is a self-balancing Binary Search Tree (BST) where every node follows following
rules.

1. Every node has a color either red or black.


2. Root of tree is always black.
3. There are no two adjacent red nodes (A red node cannot have a red parent or red child).
4. Every path from a node (including root) to any of its descendant NULL node has the same
number of black nodes.

A red-black tree is a binary search tree with one extra attribute for each node: the colour, which is
either red or black. Red-Black tree's node structure is
struct Node
{
int data;
bool color;
struct Node *right_child;
struct Node *left_child;
};
Why Red-Black Trees?
 Most of the BST operations (e.g., search, max, min, insert, delete and etc) take O(h) time
where h is the height of the BST.
 The cost of these operations may become O(h) for a skewed Binary tree. If we make sure
that height of the tree remains O(Log h) after every insertion and deletion, then we can
guarantee an upper bound of O(Log h) for all these operations.
 The height of a Red-Black tree is always O(Log n) where n is the number of nodes in the
tree. Comparison with AVL trees are more balanced compared to Red-Black Trees, but they
may cause more rotations during insertion and deletion.

Which is Preferable AVL or Red Black Tree ?


If your application involves many frequent insertions and deletions, then Red Black trees should be
preferred. And if the insertions and deletions are less frequent and search is a more frequent
operation, then AVL tree should be preferred over Red-Black Tree.

Black Height of a Red-Black Tree :

Black height is number of black nodes on a path from root to a leaf. Leaf nodes are also counted
black nodes.
From above properties 3 and 4, we can derive a
Red-Black Tree of height h has black-height >= h/2.
Advantages of Red Black Tree
 Red black tree are useful when we need insertion and deletion relatively frequent.
 Red-black trees are self-balancing so these operations are guaranteed to be O(logn).
 They have relatively low constants in a wide variety of scenarios.

Insertion Operation of Red-Black Tree

In AVL tree insertion, we used rotation as a tool to do balancing after insertion caused imbalance.
In Red-Black tree, we use two tools to do balancing.

 Recoloring
 Rotation
We try recoloring first, if recoloring doesn’t work, then we go for rotation. Following is detailed
algorithm. The algorithms has mainly two cases depending upon the color of uncle. If uncle is red,
we do recoloring. If uncle is black, we do rotations and/or recoloring.
Let x be the newly inserted node.
1) Perform standard BST insertion and make the color of newly inserted nodes as RED.
2) If x is root, change color of x as BLACK (Black height of complete tree increases by 1).
3) Do following if color of x’s parent is not BLACK and x is not root.
a) If x’s uncle is RED (Grand parent must have been black from Red)
i) Change color of parent and uncle as BLACK.
ii) color of grand parent as RED.
iii) Change x = x’s grandparent, repeat steps 2 and 3 for new x.

b) If x’s uncle is BLACK, then there can be four configurations for x, x’s parent (p) and x’s
grandparent (g) (This is similar to AVL Tree)
 Left Left Case (p is left child of g and x is left child of p)
 Left Right Case (p is left child of g and x is right child of p
 Right Right Case (Mirror of case i)
 Right Left Case (Mirror of case ii)

Following are operations to be performed in four subcases when uncle is BLACK.


All four cases when Uncle is BLACK:
Left Left Case (See g, p and x) :

Left Right Case (See g, p and x)


Right Right Case (See g, p and x)

Right Left Case (See g, p and x)

Examples of Insertion :
Deletion Operation of Red Black Trees:
Like Insertion, recoloring and rotations are used to maintain the Red-Black properties.
In delete operation, we check color of sibling to decide the appropriate case.
The main property that violates after insertion is two consecutive reds. In delete, the main violated
property is, change of black height in subtrees as deletion of a black node may cause reduced black
height in one root to leaf path.
Deletion is fairly complex process. To understand deletion, notion of double black is used. When a
black node is deleted and replaced by a black child, the child is marked as double black. The main
task now becomes to convert this double black to single black.
Steps For Deletion:
1. Perform standard BST delete. When we perform standard delete operation in BST, we
always end up deleting a node which is either leaf or has only one child (For an internal
node, we copy the successor and then recursively call delete for successor, successor is
always a leaf node or a node with one child). So we only need to handle cases where a node
is leaf or has one child. Let v be the node to be deleted and u be the child that replaces v
(Note that u is NULL when v is a leaf and color of NULL is considered as Black).
2. Simple Case: If either u or v is red, we mark the replaced child as black (No change in black
height). Note that both u and v cannot be red as v is parent of u and two consecutive reds are
not allowed in red-black tree.

3. If Both u and v are Black.


i) Color u as double black. Now our task reduces to convert this double black to single
black. Note that If v is leaf, then u is NULL and color of NULL is considered as black.
So the deletion of a black leaf also causes a double black.

ii) Do following while the current node u is double black and it is not root. Let sibling of
node be s.
(a): If sibling s is black and at least one of sibling’s children is red, perform rotation(s).
Let the red child of s be r. This case can be divided in four subcases depending upon positions of s
and r.
(i) Left Left Case (s is left child of its parent and r is left child of s or both children
of s are red). This is mirror of right right case shown in below diagram.
(ii) Left Right Case (s is left child of its parent and r is right child). This is mirror of
right left case shown in below diagram.
(iii) Right Right Case (s is right child of its parent and r is right child of s or both
children of s are red)

(iv) Right Left Case (s is right child of its parent and r is left child of s)

(b): If sibling is black and its both children are black, perform recoloring, and recur for the
parent if parent is black.

In this case, if parent was red, then we didn’t need to recur for prent, we can simply make it black
(red + double black = single black)
(c): If sibling is red, perform a rotation to move old sibling up, recolor the old sibling and parent.
The new sibling is always black (See the below diagram). This mainly converts the tree to black
sibling case (by rotation) and leads to case (a) or (b). This case can be divided in two subcases.
(i) Left Case (s is left child of its parent). This is mirror of right right case shown in below
diagram. We right rotate the parent p.
(ii) Right Case (s is right child of its parent). We left rotate the parent p.
iii) If u is root, make it single black and return (Black height of complete tree reduces by 1).

Splay Tree :
Like AVL and Red-Black Trees, Splay tree is also self-balancing BST. The main idea of splay tree
is to bring the recently accessed item to root of the tree, this makes the recently searched item to be
accessible in O(1) time if accessed again. The idea is to use locality of reference (In a typical
application, 80% of the access are to 20% of the items). Imagine a situation where we have millions
or billions of keys and only few of them are accessed frequently, which is very likely in many
practical applications.
All splay tree operations run in O(log n) time on average, where n is the number of entries in the
tree. Any single operation can take Theta(n) time in the worst case.
The worst case time complexity of Binary Search Tree (BST) operations like search, delete, insert is
O(n). The worst case occurs when the tree is skewed. We can get the worst case time complexity as
O(log n) with AVL and Red-Black Trees.
Operations on splay tree are Insert , Delete , Search.

Search Operation:
The search operation in Splay tree does the standard BST search, in addition to search, it also splays
(move a node to the root). If the search is successful, then the node that is found is splayed and
becomes the new root. Else the last node accessed prior to reaching the NULL is splayed and
becomes the new root.
There are following cases for the node being accessed.
Node is root : We simply return the root, don’t do anything else as the accessed node is already
root.
Otherwise Rotations are performed ,
Zig Rotation :
The Zig Rotation in splay tree is similar to the single right rotation in AVL Tree rotations. In zig
rotation, every node moves one position to the right from its current position.
Consider the following example...

Zag Rotation
The Zag Rotation in splay tree is similar to the single left rotation in AVL Tree rotations. In zag
rotation, every node moves one position to the left from its current position. Consider the following
example...

Zig-Zig Rotation
The Zig-Zig Rotation in splay tree is a double zig rotation. In zig-zig rotation, every node moves
two positions to the right from its current position. Consider the following example...
Zag-Zag Rotation
The Zag-Zag Rotation in splay tree is a double zag rotation. In zag-zag rotation, every node moves
two positions to the left from its current position. Consider the following example...

Zig-Zag Rotation
The Zig-Zag Rotation in splay tree is a sequence of zig rotation followed by zag rotation. In zig-zag
rotation, every node moves one position to the right followed by one position to the left from its
current position. Consider the following example...

Zag-Zig Rotation
The Zag-Zig Rotation in splay tree is a sequence of zag rotation followed by zig rotation. In zag-zig
rotation, every node moves one position to the left followed by one position to the right from its
current position. Consider the following example...
Note:Every Splay tree must be a binary search tree but it is need not to be balanced tree.

Example:

The important thing to note is, the search or splay operation not only brings the searched key to
root, but also balances the BST. For example in above case, height of BST is reduced by 1

Insertion Operation Of Splays:


Following are different cases to insert a key k in splay tree:
1) Root is NULL: We simply allocate a new node and return it as root.
2) Splay the given key k. If k is already present, then it becomes the new root. If not present, then
last accessed leaf node becomes the new root.
3) If new root’s key is same as k, don’t do anything as k is already present.
4) Else allocate memory for new node and compare root’s key with k.
a) If k is smaller than root’s key, make root as right child of new node, copy left child of root
as left child of new node and make left child of root as NULL.
b) If k is greater than root’s key, make root as left child of new node, copy right child of root as
right child of new node and make right child of root as NULL.
5) Return new node as new root of tree.
Example:
Deletion Operation Of Splays:
1) If Root is NULL: We simply return the root.
2) Else Splay the given key k. If k is present, then it becomes the new root. If not present, then last
accessed leaf node becomes the new root.
3) If new root’s key is not same as k, then return the root as k is not present.
4) Else the key k is present.
a) Split the tree into two trees Tree1 = root’s left subtree and Tree2 = root’s right subtree and
delete the root node.
b) Let the root’s of Tree1 and Tree2 be Root1 and Root2 respectively.
c) If Root1 is NULL: Return Root2.
d) Else, Splay the maximum node (node having the maximum value) of Tree1.
e) After the Splay procedure, make Root2 as the right child of Root1 and return Root1.
Advantages Of Splay Trees:
1) Splay trees have excellent locality properties. Frequently accessed items are easy to find.
Infrequent items are out of way.
2) All splay tree operations take O (Log n) time on average. Splay trees can be rigorously shown to
run in O(log n) average time per operation, over any sequence of operations (assuming we start
from an empty tree)
3) Splay trees are simpler compared to AVL and Red-Black Trees as no extra field is required in
every tree node.
4) Unlike AVL tree, a splay tree can change even with read-only operations like search.
Applications of Splay Trees:

 Splay trees have become the most widely used basic data structure invented in the last 30
years, because they’re the fastest type of balanced search tree for many applications.

 Splay trees are used in Windows NT (in the virtual memory, networking, and file system
code), the gcc compiler and GNU C++ library, the sed string editor, Fore Systems network
routers, the most popular implementation of Unix malloc, Linux loadable kernel modules,
and in much other software.

Potrebbero piacerti anche