Ds-Unit 3
Ds-Unit 3
Tree
In linear data structure data is organized in sequential order and in non-linear data structure data is organized in
random order. A tree is a very popular non-linear data structure used in a wide range of applications. A tree data
structure can be defined as follows...
• Tree is a non-linear data structure which organizes data in hierarchical structure and this is a recursive
definition.
In tree data structure, every individual element is called as Node. Node in a tree data structure stores the actual data
of that particular element and link to next element in hierarchical structure.
In a tree data structure, if we have N number of nodes then we can have a maximum of N-1 number of links.
Ex:
Terminology
In a tree data structure, we use the following terminology...
Root
In a tree data structure, the first node is called as Root Node. Every tree must have a root node. We can say that the
root node is the origin of the tree data structure. In any tree, there must be only one root node. We never have multiple
root nodes in a tree.
1
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.
Parent
In a tree data structure, the node which is a predecessor of any node is called as PARENT NODE. In simple words,
the node which has a branch from it to any other node is called a parent node. Parent node can also be defined as
"The node which has child / children".
Child
In a tree data structure, the node which is descendant of any node is called as CHILD Node. In simple words, 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.
2
Siblings
In a tree data structure, nodes which belong to same Parent are called as SIBLINGS. In simple words, the nodes with
the same parent are called Sibling nodes.
Leaf
In a tree data structure, the node which does not have a child is called as LEAF Node. In simple words, a leaf is a
node with no child.
In a tree data structure, the leaf nodes are also called as External Nodes. External node is also a node with no child.
In a tree, leaf node is also called as 'Terminal' node.
Internal Nodes
In a tree data structure, the node which has atleast one child is called as INTERNAL Node. In simple words, an
internal node is a node with atleast one child.
In a tree data structure, 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.
3
Degree
In a tree data structure, the total number of children of a node is called as DEGREE of that Node. In simple words,
the Degree of a node is total number of children it has. The highest degree of a node among all the nodes in a tree is
called as 'Degree of Tree'
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 simple words, 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).
Height
In a tree data structure, the total number of edges 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. In a tree, height of all leaf
nodes is '0'.
4
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. In a tree, the total number of edges from root node to a leaf node in the longest path is said to be Depth of the
tree. In simple words, the highest depth of any leaf node in a tree is said to be depth of that tree. In a tree, depth of
the root node is '0'.
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.
Sub Tree
In a tree data structure, each child from a node forms a subtree recursively. Every child node will form a subtree on
its parent node.
5
Binary Tree
In a normal tree, every node can have any number of children. A binary tree is a special type of tree data structure in
which every node can have a maximum of 2 children. One is known as a left child and the other is known as right
child.
• A tree in which every node can have a maximum of two children is called Binary Tree.
In a binary tree, every node can have either 0 children or 1 child or 2 children but not more than 2 children.
Ex:
6
2. Complete Binary Tree
In a binary tree, every node can have a maximum of two children. But in strictly binary tree, every node should have
exactly two children or none and in complete binary tree all the nodes must have exactly two children and at every
level of complete binary tree there must be 2 level number of nodes. For example at level 2 there must be 2 2 = 4 nodes
and at level 3 there must be 23 = 8 nodes.
• A binary tree in which every internal node has exactly two children and all leaf nodes are at same level is
called Complete Binary Tree.
Complete binary tree is also called as Perfect Binary Tree
In above figure, a normal binary tree is converted into full binary tree by adding dummy nodes (In pink colour).
7
1. Array Representation of Binary Tree
In array representation of a binary tree, we use one-dimensional array (1-D Array) to represent a binary tree.
Consider the above example of a binary tree and it is represented as follows...
To represent a binary tree of depth 'n' using array representation, we need one dimensional array with a maximum
size of 2n + 1.
The above example of the binary tree represented using Linked list representation is shown as follows...
8
Binary Tree
Traversals
When we wanted to display a binary tree, we need to follow some order in which all the nodes of that binary tree
must be displayed. In any binary tree, displaying order of nodes depends on the traversal method.
• Displaying (or) visiting order of nodes in a binary tree is called as Binary Tree Traversal.
There are three types of binary tree traversals.
1. In - Order Traversal
2. Pre - Order Traversal
3. Post - Order Traversal
Consider the following binary tree...
I-D-J-B-F-A-G-K -C-H
9
2. Pre - Order Traversal ( root - leftChild - rightChild )
In Pre-Order traversal, the root node is visited before the left child and right child nodes. In this traversal, the root
node is visited first, then its left child and later its right child. This pre-order traversal is applicable for every root
node of all subtrees in the tree.
In the above example of binary tree, first we visit root node 'A' then visit its left child 'B' which is a root for D and F.
So we visit B's left child 'D' and again D is a root for I and J. So we visit D's left child 'I' which is the leftmost child.
So next we go for visiting D's right child 'J'. With this we have completed root, left and right parts of node D and
root, left parts of node B. Next visit B's right child 'F'. With this we have completed root and left parts of node A. So
we go for A's right child 'C' which is a root node for G and H. After visiting C, we go for its left child 'G' which is a
root for node K. So next we visit left of G, but it does not have left child so we go for G's right child 'K'. With this,
we have completed node C's root and left parts. Next visit C's right child 'H' which is the rightmost child in the tree.
So we stop the process.
That means here we have visited in the order of A-B-D-I-J-F-C-G-K-H using Pre-Order Traversal.
• Pre-Order Traversal for above example binary tree is
A-B-D-I-J-F-C-G-K-H
I-J-D-F-B-K-G-H-C–A
10
//Binary Tree Display using In-Order Traversals
#include<stdio.h>
#include<conio.h>
struct Node{
int data;
struct Node *left;
struct Node *right;
};
void main(){
int choice, value;
clrscr();
printf("\n----- Binary Tree -----\n");
while(1){
printf("\n***** MENU *****\n");
printf("1. Insert\n2. Display\n3. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("\nEnter the value to be insert: ");
scanf("%d", &value);
root = insert(root,value);
break;
case 2: display(root); break;
case 3: exit(0);
default: printf("\nPlease select correct operations!!!\n");
}
}
}
11
Search
Trees
Binary Search Tree
In a binary tree, every node can have a maximum of two children but there is no need to maintain the order of nodes
basing on their values. In a binary tree, the elements are arranged in the order they arrive at the tree from top to
bottom and left to right.
A binary tree has the following time complexities...
1. Search Operation – O(n)
2. Insertion Operation – O(1)
3. Deletion Operation – O(n)
To enhance the performance of binary tree, we use a special type of binary tree known as Binary Search Tree. Binary
search tree mainly focuses on the search operation in a binary tree. Binary search tree can be defined as follows...
• Binary Search Tree is a binary tree in which every node contains only smaller values in its left subtree and
only larger values in its right subtree.
In a binary search tree, all the nodes in the left subtree of any node contains smaller values and all the nodes in the
right subtree of any node contains larger values as shown in the following figure..
Ex:
The following tree is a Binary Search Tree. In this tree, left subtree of every node contains nodes with smaller values
and right subtree of every node contains larger values.
12
• Every binary search tree is a binary tree but every binary tree need not to be binary search tree.
13
Deletion Operation in
BST
In a binary search tree, the deletion operation is performed with O(log n) time complexity. Deleting a node from
Binary search tree includes following three cases...
Case 1: Deleting a Leaf node (A node with no children)
Case 2: Deleting a node with one child
Case 3: Deleting a node with two children
14
15
//Binary Search Tree Implementation
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
int main()
{
int n , i;
struct node *p , *q , *root;
printf("Enter the number of nodes to be insert: ");
scanf("%d",&n);
for(i=0;i<i++)
{
p = (struct node*)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->left = NULL;
p->right = NULL;
if(i == 0)
{
root = p; // root always point to the root node
}
else
{
q = root; // q is used to traverse the tree
while(1)
{
if(p->data > q->data)
{
if(q->right == NULL)
{
q->right = p;
break;
}
else
q = q->right;
}
else
{
if(q->left == NULL)
{
q->left = p;
break;
}
else
q = q->left;
}
}
return 0;
}
16
AVL Tree
AVL tree is a height-balanced binary search tree. That means, an AVL tree is also a binary search tree but it is a
balanced tree. A binary tree is said to be balanced if, the difference between the heights of left and right subtrees of
every node in the tree is either -1, 0 or +1. In other words, a binary tree is said to be balanced if the height of left and
right children of every node differ by either -1, 0 or +1. In an AVL tree, every node maintains an extra information
known as balance factor. The AVL tree was introduced in the year 1962 by G.M. Adelson-Velsky and E.M. Landis.
An AVL tree is defined as follows...
• An AVL tree is a balanced binary search tree. In an AVL tree, balance factor of every node is either -1, 0 or +1.
Balance factor of a node is the difference between the heights of the left and right subtrees of that node. The balance
factor of a node is calculated either height of left subtree - height of right subtree (OR) height of right subtree -
height of left subtree. In the following explanation, we calculate as follows...
Balance factor = heightOfLeftSubtree – heightOfRightSubtree
Ex:
The above tree is a binary search tree and every node is satisfying balance factor condition. So this tree is said to be
an AVL tree.
• Every AVL Tree is a binary search tree but every Binary Search Tree need not be AVL tree.
17
Single Left Rotation (LL
Rotation)
In LL Rotation, every node moves one position to left from the current position. To understand LL Rotation, let us
consider the following insertion operation in AVL Tree...
18
Operations on an AVL Tree
The following operations are performed on AVL tree...
1. Search
2. Insertion
3. Deletion
19
20
Deletion Operation in AVL
Tree
The deletion operation in AVL Tree is similar to deletion operation in BST. But after every deletion operation, we
need to check with the Balance Factor condition. If the tree is balanced after deletion go for next operation otherwise
perform suitable rotation to make the tree Balanced.
Red - Black
Red - Black Tree is another variant of Binary Search Tree in which every node is colored either RED or BLACK. We
can define a Red Black Tree as follows...
• Red Black Tree is a Binary Search Tree in which every node is colored either RED or BLACK.
In Red Black Tree, the color of a node is decided based on the properties of Red-Black Tree. Every Red Black Tree
has the following properties.
The above tree is a Red-Black tree where every node is satisfying all the properties of Red-Black Tree.
• Every Red Black Tree is a binary search tree but every Binary Search Tree need not be Red Black tree.
21
1. Recolor
2. Rotation
3. Rotation followed by Recolor
The insertion operation in Red Black tree is performed using the following steps...
Step 1 - Check whether tree is Empty.
Step 2 - If tree is Empty then insert the newNode as Root node with color Black and exit from the operation.
Step 3 - If tree is not Empty then insert the newNode as leaf node with color Red.
Step 4 - If the parent of newNode is Black then exit from the operation.
Step 5 - If the parent of newNode is Red then check the color of parentnode's sibling of newNode.
Step 6 - If it is colored Black or NULL then make suitable Rotation and Recolor it.
Step 7 - If it is colored Red then perform Recolor. Repeat the same until tree becomes Red Black Tree.
Ex:
22
23
Deletion Operation in Red Black
Tree
The deletion operation in Red-Black Tree is similar to deletion operation in BST. But after every deletion operation,
we need to check with the Red-Black Tree properties. If any of the properties are violated then make suitable
operations like Recolor, Rotation and Rotation followed by Recolor to make it Red-Black Tree.
Splay Tree
Splay tree is another variant of a binary search tree. In a splay tree, recently accessed element is placed at the root of
the tree. A splay tree is defined as follows...
• Splay Tree is a self - adjusted Binary Search Tree in which every operation on element rearranges the tree so
that the element is placed at the root position of the tree.
In a splay tree, every operation is performed at the root of the tree. All the operations in splay tree are involved with a
common operation called "Splaying".
• Splaying an element, is the process of bringing it to the root position by performing suitable rotation
operations.
In a splay tree, splaying an element rearranges all the elements in the tree so that splayed element is placed at the root
of the tree.
By splaying elements we bring more frequently used elements closer to the root of the tree so that any operation on
those elements is performed quickly. That means the splaying operation automatically brings more frequently used
elements closer to the root of the tree.
Every operation on splay tree performs the splaying operation. For example, the insertion operation first inserts the
new element using the binary search tree insertion process, then the newly inserted element is splayed so that it is
placed at the root of the tree. The search operation in a splay tree is nothing but searching the element using binary
search process and then splaying that searched element so that it is placed at the root of the tree.
In splay tree, to splay any element we use the following rotation operations...
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...
24
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...
25
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...
• Every Splay tree must be a binary search tree but it is need not to be balanced tree.