0% found this document useful (0 votes)
25 views77 pages

Unit 4

this is the unit 4 of dsa

Uploaded by

preritsinghcr7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views77 pages

Unit 4

this is the unit 4 of dsa

Uploaded by

preritsinghcr7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Unit :4

Tree
Tree Definition

Tree is a non-linear data structure which


organizes data in hierarchical structure and
this is a recursive definition.
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.
Tree terminology...
 1.Root:
 The first node is called as Root Node.
 Every tree must have root node, there must be
only one root node.
 Root node doesn't have any parent.
2. Edge
 In a tree data structure, the connecting link between any
two nodes is called as EDGE. In a tree with 'N' number of
nodes there will be a maximum of 'N-1' number of edges.
3. Parent
 In a tree data structure, the node which is predecessor of any
node is called as PARENT NODE. In simple words, the node
which has branch from it to any other node is called as parent
node. Parent node can also be defined as "The node which
has child / children".
4. Child
 The node which has a link from its parent node is called as child node.
 In a tree, any parent node can have any number of child nodes.
 In a tree, all the nodes except root are child nodes.
5. Siblings
 The nodes with same parent are called as
Sibling nodes.
6. Leaf Node
 The node which does not have a child is called as LEAF
Node.
 The leaf nodes are also called as External Nodes or
'Terminal' node.
7. Internal Nodes
 An internal node is a node with atleast one child.
 Nodes other than leaf nodes are called as Internal Nodes.
 The root node is also said to be Internal Node if the tree has
more than one node. Internal nodes are also called as 'Non-
Terminal' nodes.
8. Degree
 In a tree data structure, the total number of
children of a node is called as DEGREE of that
Node.
9. Level
 In a tree data structure, the root node is said to be at Level 0 and
the children of root node are at Level 1 and the children of the
nodes which are at Level 1 will be at Level 2 and so on...
 In a tree each step from top to bottom is called as a Level and the
Level count starts with '0' and incremented by one at each level
(Step).
10. Height
 the total number of egdes from leaf node to a particular node in the
longest path is called as HEIGHT of that Node.
 In a tree, height of the root node is said to be height of the tree.
11. Depth
 In a tree data structure, the total number of egdes from root node to
a particular node is called as DEPTH of that Node.
12. Path
 In a tree data structure, the sequence of Nodes and Edges from
one node to another node is called as PATH between that two
Nodes.
 Length of a Path is total number of nodes in that path. In below
example the path A - B - E - J has length 4.
13. Sub Tree
 Every child node will form a subtree on its
parent node.
Type of Trees
• General tree
• Binary tree
• Binary Search Tree
General Tree
• A general tree is a data structure in that each node can have infinite
number of children .
• In general tree, root has in-degree 0 and maximum out-degree n.
• Height of a general tree is the length of longest path from root to the leaf
of tree. Height(T) = {max(height(child1) , height(child2) , … height(child-n)
) +1}

Binary tree
• A Binary tree is a data structure in that each node has at most two
nodes left and right
• In binary tree, root has in-degree 0 and maximum out-degree 2.
• In binary tree, each node have in-degree one and maximum out-
degree 2.
• Height of a binary tree is : Height(T) = { max (Height(Left Child) ,
Height(Right Child) + 1}
Binary Tree Types

1. Extended Binary Tree


2. Complete Binary Tree
3. Full Binary Tree
4. Skewed Binary Tree
5. Strictly Binary Tree
6. Almost Complete Binary tree
Extended Binary Tree

• Extended binary tree is a


type of binary tree in which
all the null sub tree of the
original tree are replaced with
special nodes called external
nodes whereas other nodes
are called internal nodes
• Here the circles represent the
internal nodes and the boxes
represent the external nodes.
Properties of External
binary tree
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.
Properties of Complete Binary
Tree
• The maximum number of nodes in complete
binary tree is 2h+1 - 1.
• The minimum number of nodes in complete
binary tree is 2h.
Full 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. The full binary
tree can also be defined
as the tree in which each
node must contain 2
children except the leaf
nodes.
Properties of Full Binary Tree
• The number of leaf nodes is equal to the number of internal
nodes plus 1. In the above example, the number of internal
nodes is 5; therefore, the number of leaf nodes is equal to 6.
• The maximum number of nodes is the same as the number of
nodes in the binary tree, i.e., 2h+1 -1.
• The minimum number of nodes in the full binary tree is 2*h-1.
• The minimum height of the full binary tree is log2(n+1) - 1.
• The maximum height of the full binary tree can be computed
as:
• n= 2*h - 1
• n+1 = 2*h
• h = n+1/2
Skewed Binary Tree

• A skewed binary tree is a


pathological/degenerate
tree(each node has one
child) in which the tree is
either dominated by the
left nodes or the right
nodes. Thus, there are
two types of skewed
binary tree: left-skewed
binary tree and right-
skewed binary tree.
Strict Binary Tree
• A Strict Binary Tree is also known
as Proper Binary Tree and Full
Binary Tree. A Binary Tree is
identified as a Strict Binary Tree if
each parent node contains either
no or two children. All nodes
contain two children in a Strict
Binary Tree except the leaf nodes
which have 0 children.
• The above figure is an example of
a Strict Binary Tree. The internal
nodes (node 1, node 2, node 3,
node 5) have 2 children each,
whereas the leaf nodes (node 4,
node 6, node 7, node 8, node 9)
have no children.
Almost Complete Binary Tree

• An almost complete binary tree


is a special kind of binary tree
where insertion takes place level
by level and from left to right
order at each level and the last
level is not filled fully always. It
also contains nodes at each level
except the last level.
• The main point here is that if we
want to insert any node at the
lowest level of the tree, it should be
inserted from the left. All the
internal nodes should be
completely filled.
• An almost complete tree is also
a complete binary tree.
Binary Search Tree
A binary search tree (BST) or
"ordered binary tree" is a empty or in which
each node contains a key that satisfies
following conditions:
1. All keys are distinct.’
2. , all elements in its left subtree are less to the node
(<), and all the elements in its right subtree are greater
than the node (>).
Binary search tree
Binary search tree property
For every node X
All the keys in its left
subtree are smaller than
the key value in X
All the keys in its right
subtree are larger than the
key value in X
Binary Search Trees

A binary search tree Not a binary search tree


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
Preoder, Inorder, Postorder
• In Preorder, the root
is visited before (pre)
the subtrees traversals
• In Inorder, the root is
visited in-between left
and right subtree
traversal
• In Preorder, the root
is visited after (pre)
the subtrees traversals
Illustrations for Traversals
• Assume: visiting a node
is printing its label
• Preorder:
1 3 5 4 6 7 8 9 10 11 12
• Inorder:
4 5 6 3 1 8 7 9 11 10 12
• Postorder:
4 6 5 3 8 11 12 10 9 7 1
Illustrations for Traversals
(Contd.)
• Assume: visiting a node 15

is printing its data


8 20
• Preorder: 15 8 2 6 3 7
11 10 12 14 20 27 22 30 2 11 27

• Inorder: 2 3 6 7 8 10 11
12 14 15 20 22 27 30 6 10 22 30
12
• Postorder: 3 7 6 2 10 14
12 11 8 22 30 27 20 15 3 7 14
Algorithm for Traversal
• Preorder traversal Algorithm:
Until all nodes of the tree are no
t visited
• Step 1 - Visit the root node
• Step 2 -
Traverse the left subtree rec
ursively.
• Step 3 -
Traverse the right subtree re
cursively.
Postorder traversal

Until all nodes of the tree


are not visited

• Step 1 -
Traverse the left subtree
recursively.
• Step 2 -
Traverse the right subtre
e recursively.
• Step 3 -
Visit the root node.
Inorder traversal

Until all nodes of the tree


are not visited

• Step 1 -
Traverse the left subtree
recursively.
• Step 2 -
Visit the root node.
• Step 3 -
Traverse the right subtre
e recursively.
Write a program to implement tree
traversal techniques in C.
• #include <stdio.h>
• #include <stdlib.h>

• struct node {
• int element;
• struct node* left;
• struct node* right;
• };
Contd..
• /*To create a new node*/
• struct node* createNode(int val)
• {
• struct node* Node = (struct node*)malloc(si
zeof(struct node));
• Node->element = val;
• Node->left = NULL;
• Node->right = NULL;

• return (Node);
• }
/*function to traverse the nodes of binary tree in preorder*/
void traversePreorder(struct node* root)
{
if (root == NULL)
return;
printf(" %d ", root->element);
traversePreorder(root->left);
traversePreorder(root->right);
}

/*function to traverse the nodes of binary tree in Inorder*/


void traverseInorder(struct node* root)
{
if (root == NULL)
return;
traverseInorder(root->left);
printf(" %d ", root->element);
traverseInorder(root->right);
}
/*function to traverse the nodes of binary tree in postorder*/
void traversePostorder(struct node* root)
{
if (root == NULL)
return;
traversePostorder(root->left);
traversePostorder(root->right);
printf(" %d ", root->element);
}
int main()
{
struct node* root = createNode(36);
root->left = createNode(26);
root->right = createNode(46);
root->left->left = createNode(21);
root->left->right = createNode(31);
root->left->left->left = createNode(11);
root->left->left->right = createNode(24);
root->right->left = createNode(41);
root->right->right = createNode(56);
root->right->right->left = createNode(51);
root->right->right->right = createNode(66);

printf("\n The Preorder traversal of given binary tree is -\n");


traversePreorder(root);

printf("\n The Inorder traversal of given binary tree is -\n");


traverseInorder(root);

printf("\n The Postorder traversal of given binary tree is -\n");


traversePostorder(root);

return 0;
}
What is a Binary Search tree?
• A binary search tree follows
some order to arrange the
elements. In a Binary search
tree, the value of left node
must be smaller than the
parent node, and the value of
right node must be greater
than the parent node. This
rule is applied recursively to
the left and right subtrees of
the root.
• Let's understand the concept
of Binary search tree with an
example.
In the above figure, we can observe that the root node is 40, and all the nodes of the
left subtree are smaller than the root node, and all the nodes of the right subtree are
greater than the root node.
Example of creating a binary search
tree
• Suppose the data elements are - 45, 15, 79,
90, 10, 55, 12, 20, 50
• First, we have to insert 45 into the tree as the
root of the tree.
• Then, read the next element; if it is smaller
than the root node, insert it as the root of the
left subtree, and move to the next element.
• Otherwise, if the element is larger than the root
node, then insert it as the root of the right
subtree.
Contd…
• Step 1 - Insert 45. • Step 3 - Insert 79.
• As 79 is greater than 45,
so insert it as the root
node of the right subtree.

• Step 2 - Insert 15.


• As 15 is smaller than 45,
so insert it as the root
node of the left subtree.
Step 4 - Insert 90.
90 is greater than 45 and 79, so it will
be inserted as the right subtree of 79.
Contd….
• Step 6 - Insert 55.
• 55 is larger than 45 and smaller
than 79, so it will be inserted as the
left subtree of 79.

Step 5 - Insert 10.


10 is smaller than 45 and 15, so it
will be inserted as a left subtree of
15.

Step 7 - Insert 12.


12 is smaller than 45 and 15 but
greater than 10, so it will be inserted as
the right subtree of 10.
Contd…

Step 8 - Insert 20.


20 is smaller than 45 but greater than 15,
so it will be inserted as the right subtree Step 9 - Insert 50.
of 15. 50 is greater than 45 but smaller than
79 and 55. So, it will be inserted as a
left subtree of 55.
Contd..

Now, the creation of binary search


tree is completed.
Insertion in BST
• Searching means to find or locate a specific element or node in a data
structure. In Binary search tree, searching a node is easy because
elements in BST are stored in a specific order. The steps of searching a
node in Binary Search tree are listed as follows -
• First, compare the element to be searched with the root element of the tree.
• If root is matched with the target element, then return the node's location.
• If it is not matched, then check whether the item is less than the root
element, if it is smaller than the root element, then move to the left subtree.
• If it is larger than the root element, then move to the right subtree.
• Repeat the above procedure recursively until the match is found.
• If the element is not found or not present in the tree, then return NULL.
Contd…
• Suppose we have to find • Step2:
node 20 from the below
tree.
Contd…
• Step3: • Algorithm to search an element
in Binary search tree
• Search (root, item)
• Step 1 -
if (item = root → data) or (root = N
ULL)
• return root
• else if (item < root → data)
• return Search(root → left, item)
• else
• return Search(root → right, item)
• END if
• Step 2 - END
Advantages of Binary search tree

• Searching an element in the Binary search tree


is easy as we always have a hint that which
subtree has the desired element.
• As compared to array and linked lists, insertion
and deletion operations are faster in BST.
Binary Search Tree - Deletion
• Let’s consider several cases for Deletion:
• 1) Deleting a Leaf node
• 2) Deleting a node with 1 child
• 3) Deleting a node with 2 children For all
cases we have to identify the parent.

• Note:we must delete a node from a binary


search tree in such a way, that the property of
binary search tree doesn't violate.
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 simple free the
allocated space.
• In the following image,
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.
The node to be deleted has only one child

• In this case, replace the node with


its child and delete the child node,
which now contains the value
which is to be deleted. Simply
replace it with the NULL and free
the allocated space.

• In the following image, 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.
• Deleting a node with 2 children:
• In order to maintain the BST
property ,
• we can replace the deleted node
with either:
• Max in the left subtree.
• OR Min in the right subtree
• In the following image, the node 50
is to be deleted which is the root
node of the tree.
Algorithm to perform Deletion in BST:
• Delete (TREE, ITEM)
• Step 1: IF TREE = NULL
Write "item not found in the tree" ELSE IF ITEM < TREE -> DATA
Delete(TREE->LEFT, ITEM)
ELSE IF ITEM > TREE -> DATA
Delete(TREE -> RIGHT, ITEM)
ELSE IF TREE -> LEFT AND TREE -> RIGHT
SET TEMP = findLargestNode(TREE -> LEFT)
SET TREE -> DATA = TEMP -> DATA
Delete(TREE -> LEFT, TEMP -> DATA)
ELSE
SET TEMP = TREE
IF TREE -> LEFT = NULL AND TREE -> RIGHT = NULL
SET TREE = NULL
ELSE IF TREE -> LEFT != NULL
SET TREE = TREE -> LEFT
ELSE
SET TREE = TREE -> RIGHT
[END OF IF]
FREE TEMP
[END OF IF]
• Step 2: END
AVL Tree
• 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.
• Tree is said to be balanced if balance factor of
each node is in between -1 to 1, otherwise, the
tree will be unbalanced and need to be
balanced.
• Balance Factor (k) = height (left(k)) - height
(right(k))
Contd…
• 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.
Operations on AVL tree
AVL Rotations

• We perform rotation in AVL tree only in case if Balance Factor is other


than -1, 0, and 1. There are basically four types of rotations which are as
follows:

• 1. 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
Contd..
• 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.
Contd..
• 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, by full tree we mean the first
node from the path of inserted node whose balance
factor is other than -1, 0, or 1.
• Let us understand each and every step very
clearly:
Contd..
Contd..
• RL Rotation
• 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, by full tree we mean the first node from the path of
inserted node whose balance factor is other than -1, 0, or 1.

Let us understand each and every step very clearly:
Construct an AVL tree having the following elements

• H, I, J, B, A, E, C, F, D, G, K,
L

On inserting the above elements,


especially in the case of H, the BST
becomes unbalanced as the Balance
Factor of H is -2. Since the BST is right-
skewed, we will perform RR Rotation on
node H.

On inserting the above elements, especially in case of A, the BST becomes


unbalanced as the Balance Factor of H and I is 2, we consider the first node from the
last inserted node i.e. H. Since the BST from H is left-skewed, we will perform LL
Rotation on node H.
• On inserting E, BST becomes
unbalanced as the Balance Factor of I
is 2, since if we travel from E to I we
find that it is inserted in the left subtree
of right subtree of I, we will perform LR
Rotation on node I. LR = RR + LL
rotation
• On inserting C, F, D, BST becomes
unbalanced as the Balance Factor of B and
H is -2, since if we travel from D to B we find
that it is inserted in the right subtree of left
subtree of B, we will perform RL Rotation on
node I. RL = LL + RR rotation.
• 4a) We first perform LL rotation on node
E
• On inserting G, BST become
unbalanced as the Balance Factor of H
is 2, since if we travel from G to H, we
find that it is inserted in the left subtree
of right subtree of H, we will perform LR
Rotation on node I. LR = RR + LL
rotation.
• On inserting K, BST becomes
unbalanced as the Balance Factor of I
is -2. Since the BST is right-skewed
from I to K, hence we will perform RR
Rotation on the node I.
• 7. Insert L
• On inserting the L tree is still
balanced as the Balance Factor of
each node is now either, -1, 0, +1.
Hence the tree is a Balanced AVL
tree

You might also like