0% found this document useful (0 votes)
20 views22 pages

Unit 005-TREES

The document provides an extensive overview of binary trees, including their definitions, properties, types, and applications. It explains key terminologies such as root, edge, parent, child, and various traversal methods like pre-order, in-order, and post-order. Additionally, it discusses binary search trees and their characteristics, emphasizing their importance in data structures and algorithms.
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)
20 views22 pages

Unit 005-TREES

The document provides an extensive overview of binary trees, including their definitions, properties, types, and applications. It explains key terminologies such as root, edge, parent, child, and various traversal methods like pre-order, in-order, and post-order. Additionally, it discusses binary search trees and their characteristics, emphasizing their importance in data structures and algorithms.
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/ 22

Binary Trees: Introduction to Non- Linear Data Structures, introduction Binary Trees, Types of Trees, Basic

Definition of Binary Trees, Properties of Binary Trees, Representation of Binary Trees, Operations on a Binary
Search Tree, Binary Tree Traversal, Counting Number ofBinary Trees, Applications of Binary Tree.

TREE
A tree is a non-linear data structure and is generally defined as a nonempty finite set of elements,
called nodes such that:
1. It contains a special node called root of the tree.
2. Others all nodes are partitioned under root, and should exist one path between any pairs of nodes.
(It doesn’t form any cycle).

Tree Terminologies:
In a tree data structure, we use the following terminology...

1. Root:
In a tree data structure, the first node is called as Root Node. Every tree must have root node.
We can say that root node is the origin of tree data structure. In any tree, there must be only
one root node. We never have multiple root nodes in a tree.

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

5. Siblings:
In a tree data structure, nodes which belong to same Parent are called as SIBLINGS. In
simple words, the nodes with same parent are called as Sibling nodes.
6. Leaf:
In a tree data structure, the node which does not have a child is called as LEAFNode. 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.

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

8. 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'

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 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).
10. 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'.

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. 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'.

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

BINARY TREE
A binary tree is defined as a finite set of elements, called nodes, such that:
1 Tree is empty (called the null tree or empty tree) or
2 Tree contains a distinguished node called root node, and the remaining nodes form
anordered pair of disjoint nodes less than two only.
3 A tree T is said to be binary tree if there exists exactly 0,1,2 children nodes for each
node of the tree i.e.,the number of children of a node is at most 2.
In the above tree-
“A” is the root node and “B”
and “C” are called subtrees.
B and C are left and right successor of A. The
node A is called parent node
B and C are called children.
All lower level nodes are called descendants
All upper level nodes are called ancestors of their descendants.
The line drawn between parent and child is called an edge the
line(s) between and ancestor and descendant is called path.
A node without any children is called a terminal or leaf node A
path ending with a leaf is called a branch.

Properties of binary trees


 The depth of a binary tree containing N nodes is at most N-1.
 The depth of a binary tree containing N leaves is at least [log2(N)].
 A binary tree of depth d has at most 2d leaves.
 The number of nodes in a binary tree of depth d is at most 2d-1 - 1.
 The average depth of a binary tree containing N nodes is Ο Ν .
 The maximum number of nodes on level i of a binary tree is 2 , i i-1
1
 The maximum number of nodes in a binary tree of depth k is 2 – 1, k k
1
 If a complete binary tree with n nodes (depth = log2n +1 ) 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. left_child( i ) is at 2i if 2i n. If 2i > n, then i has no left child
3. rightt_child( i ) is at 2i + 1 if 2i + 1 n. If 2i + 1 > n, then i has no right child

TYPES OF TREES

1.Complete Binary Tree:


A binary tree is said to be complete if all its level except possibly the last,
have maximum number of possible nodes, and if all the nodes at the last
level appear as far left as possible.

2.Full binary tree:


A binary tree said to be full if all its level have maximum number of possible
node.

3. Extended Binary Tree (Strictly Binary Tree or 2-tree):


A binary tree is said to be Extended binary tree if each node has either 0 or 2 children. In this case
the leaf nodes are called external nodes and the node with two children are called internal nodes
4. Skewed Tree:
A tree is called Skew if all the nodes of a tree are attached to one side
only. i.e A left skew will not have any right children in its each node and
right skew will not have any left child in its each node.

APPLICATIONS OF BINARY TREES

 Binary Search Tree


Used in many search applications where data is constantly entering/leaving, such as the map
and set objects in many languages' libraries.

 Binary Space Partition


Used in almost every 3D video game to determine what objects need to be rendered.

 Binary Tries
Used in almost every high-bandwidth router for storing router-tables.

 Hash Trees
Used in p2p programs and specialized image-signatures in which a hash needs to be verified,
but the whole file is not available.

 Heaps
Used in implementing efficient priority-queues, which in turn are used for scheduling
processes in many operating systems, also used in heap-sort.

 Huffman Coding Tree (Chip Uni)


Used in compression algorithms, such as those used by the .jpeg and .mp3 file-formats.

 GGM Trees
Used in cryptographic applications to generate a tree of pseudo-random numbers.
BINARY-TREE REPRESENTATION
A binary tree data structure is represented in two ways.
A. Array representation
B. Linked list representation
A. ARRAY REPRESENTATION:
In array representation of binary tree, we use one-dimensional array. Let’s consider the
following tree.

1. Store the left child at 2*i+1 position, if its parent node is at ith position.
2. Store the right child at 2*i+2 position, if its parent node is at ith position.
3. We need one-dimensional array with a maximum size of 2n+1-1, to represent a binary tree of
depth “n”.
4. The above example is represented as follows.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

A B C D E F G H I - - - J - - -

Advantages:
• This method benefits from more compact storage and better locality of reference,
particularly during a preorder traversal.
Limitations:
 Wastage of space for some types of binary tree.
 Insertion and deletions require potential changes in the array.

B. LINKED REPRESENTATION:
We use double linked list to represent binary tree. In a double linked list, every node consists
of three fields. First field is used to store the left child address, second field is used to store
data, third field is used tostore right child address.

Advantages:
 Insertion and deletion involve no data movement and no movement of nodes except
the rearrangement of pointers.
Limitations:
 Given a node structure, it is difficult to determine its parent node.
 Memory spaces are wasted for storing NULL pointers for the nodes, which have no
subtrees.
BINARY TREE TRAVERSAL
There are three different types of traversing techniques to traverse a binary tree. Traversing means
visiting each and every node of a tree. The following are the different traversing techniques.
1. Pre-order traversal
2. In-order traversal
3. Post-order traversal
1. Pre-Order Traversal:
In this traversing technique, the root of the tree is visited first and followed by left sub- tree
and then right sub-tree is visited. The following is the sequence of visiting order of pre-order
traversal.
Left Right
Root
sub-tree sub-tree

Algorithm for Pre-Order Traversal: void preorder(node root)


Step-1: (check if the tree is empty by { if( root != NULL )
verifying root pointer) { print root . data;
If (p==NULL) preorder (root . lchild);
Print tree is empty preorder (root . rchild);
}
Step-2: visit root (root.data)
}
Step-3: visit left sub-tree (root.lchild)
Step-4: visit right sub-tree (root.rchild)
Step-5: exit.
Implementation:

The pre-order traversal of the above tree is as follows:


A B C H D E F G I J
2. In-Order Traversal
In this traversing technique the left sub-tree visited first followed by its root and then the right
sub-tree is visited. The following is the sequence of visiting order for an in-order traversal.
Left Right
Root
sub-tree sub-tree
Algorithm for In-Order Traversal:
Step-1: (check if the tree is empty by
verifying root pointer) void inorder(node root)
{ if(root != NULL)
If (p==NULL)
{
Print tree is empty inorder(root . lchild);
Step-2: visit left sub-tree (root.lchild) print root . data;
Step-3: visit root (root.data) inorder(root . rchild);
Step-4: visit right sub-tree (root.rchild) }
Step-5: exit }

Implementation:

The In-Order traversal of the above tree is as follows:


H C B D A F E G I J
3. Post-Order Traversal:
In this traversing technique, the left sub-tree is visited first and then right sub-tree is visited
and then root is visited. The following is the sequence of visiting order of post order.
Left Right
Root
sub-tree sub-tree

Algorithm for Post-Order Traversal:


Step-1: (check if the tree is empty by verifying void postorder(node root)
root pointer) { if( root != NULL )
If (p==NULL) { preorder (root . lchild);
preorder (root . rchild);
Print tree is empty print root . data;
Step-2: visit left sub-tree (root.lchild) Step-3: }
visit right sub-tree (root.rchild) Step-4: visit }
root (root.data)
Step-5: exit
Implementation:
The post-order traversal of the above tree is as follows:
H C D B F J I G E A
Another traversal method
LEVEL ORDER TRAVERSAL:
In a level order traversal, the nodes are visited level by level starting from the root, and going from
left to right. The level order traversal requires a queue data structure. So, it is not possible to
develop a recursive procedure to traverse the binary tree in level order. This is nothing but a
breadth first search technique. The algorithm for level order traversal is as follows:
void levelorder( )
{ int j;
for(j = 0; j < ctr; j++)
{
if(tree[j] != NULL) print
tree[j] . data;
}
}

Examples of Tree traversals

+ *

g Preorder ++a*bc*+*defg
a * + Inorder a+b*c+d*e+f*g
Postorder abc*+de*f+g*+
b c * f

d e
BINARY SEARCH TREE (BST)
First of all, binary search tree (BST) is a dynamic data structure, which means, that its size is only
limited by amount of free memory in the operating system and number of elements may vary during
the program run.
A Binary tree is said to be binary search tree if the nodes of the left sub- tree
of the root node are less than root node and the nodes of the right sub-tree of the root node are
greater than or equal to the root node.
Binary search tree is a data structure, which meets the following requirements:

•It is a binary tree;


•Each node contains a value/key;
•Every element has a value and no two elements have the same value
•The keys in the left subtree are smaller than the key in the root.
•The keys in the right subtree are larger than the key in the root.
•Notice, that definition above doesn't allow duplicates.

Let us consider the following numbers to be stored into a binary search tree.
35, 14, 10, 25, 40, 50, 45, 65
The binary search tree of above data is as follows:

TRAVERSAL OF BST
The following are the different traversing techniques.
1. Pre-order traversal
2. In-order traversal
3. Post-order traversal
1. Pre order traversal
Algorithm for Pre-Order traversal:
Step-1: visit root node (display root.data) Step-2:
visit left sub-tree preorder(root.lchild) Step-3: visit
right sub-tree preorder(root.rchild)
Pre-Order : 35 14 10 25 40 50 45 65

2. In order traversal
Algorithm for In-order traversal:
Step-1: visit left sub-tree inorder(root.lchild) Step-
2: visit root node ( display root.data) Step-3: visit
right sub-tree inorder(root.rchild)
In-Order : 10 14 25 35 40 45 50 65
3. Post order traversal
Algorithm for Post-Order traversal:
Step-1: visit left sub-tree postorder(root.lchild) Step-2:
visit right sub-tree postorder(root.rchild) Step-3: visit root
node (display root.data)

Post-Order : 10 25 14 45 65 50 40 35

OPERATIONS ON BST
In order of this binary search tree gives ascending order of the list. Operations that can be performed on binary
search tree are:
1) Searching
2) Inserting any data
3) Deleting any data from BST

1. Searching in the binary search tree:-


Searching in BST is much faster than arrays or linked list. Suppose we have to search for “ITEM” in a
binary search tree “T”. We start from root node “ROOT”. If “ITEM” is less than value in “ROOT”, we
proceed to left child. If ITEM is greater than value in ROOT, we proceed to right child. We continue
searching until we have found the desired value or reach the end of the tree.

Algorithm:
1.Read the search value
ITEM = Get value ( )
2. Initializing the variable “p” to root.
P = ROOT
3. Initialize the flag variable
flag = false;
4. Start the search process
while (p!=NULL && flag= = FALSE)
5. Check the ITEM and goto the left subtree if
(ITEM<data(p)) then p=left child(p);
6. Check the ITEM and goto right sub tree.
if (ITEM>data(p)) then p= right child (p);
7. Check the ITEM, if the ITEM is found. If
(ITEM = = data (p) then
8. Change the flag status
flag = TRUE;
End if End
while
9. Check the flag status
if (flag = = TRUE) then
print “Data item found at “, p
else
print “search unsuccess” end if
10. Finish
STOP
2. Inserting in to binary search tree:-
This is very simple and is extension of searching in binary search tree. To insert “ITEM” in to binary search
tree “T”. We start searching in “T” for “ITEM” from the root node. If “ITEM” is found in binary search tree
there is no insertion. If “ITEM” is not found then we insert it at the dead-end where the search stops.
Algorithm:-
1. Access root node
P=ROOT;
2. Read the data ITEM
ITEM=Get value ( );
3. Search for correct dead-end node
while (p!=NULL) {
4. If the ITEM is less than node data, then move to left child if
(ITEM < Data(p))
p=Left child (p);
5. If the ITEM is greater than node data, then move to right child else
if(ITEM > Data(p))
p=Right child (p);
6. If the data ITEM is available in BST then STOP the process. else
if (ITEM = = Data(p))
{
print “The node already exist”;
EXIT;
}
} // End while
7. Insert new node at END. If ITEM is less than node data then create left child. if
(ITEM < Data(p))
Left child (p) = ITEM;
8. Otherwise the ITEM stores as a right child of the node. else
if (ITEM > Data(p))
Right child (p) = ITEM;
9. Finish
STOP

3. Deleting a node from binary search tree:-


Another important function for maintaining BST is to delete a specific node form the tree. The method
to delete a node depends on the specific position of the node in the tree. The algorithm to delete a node can
be subdivided in to 3 cases.

Case (i):
If the node to be deleted is a leaf, we only need to set the appropriate link of its parent to NULL and
dispose of the node which is deleted.
Ex:
100

50
150

To delete 50 from the BST


100

NUL
L
150
Case (ii):
If the node to be deleted has only one child, we can not simply make the link of the parent to NULL. We
need to adjust the link from the parent of the deleted node to point to the child of the delete node, then
dispose of the deleted node.
Ex:
100

150

200

To delete 150 from the BST.

After dispose 150, the result BST is:

100

200
Case (iii):
The most complicated problem comes when we have to delete a node with two children. There is no way
we can make the parent of the delete node to point to both of the children of the deleted node.
Ex: 35

20 45

16 29

24 33

27
If we want to delete 20 , first we have to delete 20
and replace the node with 29

35

29 45

16 33

24

AVL Trees
A binary search tree can be maintained equal sized left and right sub trees, it is correctly suitable to efficient
searching operation. Such a binary search tree is called as balanced binary tree or AVL tree. It was developed in
the year 1962 by Adelson, Velskii and Landis.

Threaded Binary Tree (TBT):


We know that a binary tree is represented either by using arrays or by using linked list.
1. When a binary tree is represented is by using linked list, if any node is not having a child,
we use nullreference in that position.
2. In any binary tree there are more number of null references than actual
references, it wastes lot ofstorage space.

To convert a binary tree into threaded binary tree


1. Keep the null values as it is in the left-child reference of left most node and right- child
of right mostnode.
2. Write the in-order traversal of binary tree.
3. If the null reference is from left child then point it to its in-order predecessor and and
point in-ordersuccessor in case of right child.

Consider the above binary tree. We need to keep null values in left-child reference of left
most node and right-child reference of right most node.
Now the in-order traversal of the above tree is
D B E A C F
Now remove null values and replace them with in-order predecessor in case of left- child and
with in-ordersuccessor in case of right-child.

The problem with above representation is that we can‟t find the direct child and parent node
references. In-orderto achieve this we need to rearrange the node structure as follows:

Field-1 - reference of left child


Field-2 - left flag i.e., 0 or 1
Field-3 - data in that node
Field-4 - right flag i.e., 0 or 1
Field-5 - reference of right child

In fileds2 and 4 the value 0 represents left/right child references to its parent/ancestor node.
In fields2 and 4 the value 1 represents left/right child references to its direct child node.
And we create a temporary node which does not contain any data and it is referenced by left-child
of left most node and right-child of right most child. The left child reference of temporary node
points to root node and theright child references to itself.

17
Heap Tree:
Heap data structure is a specialized binary tree based data structure. Hence it is a binary tree with
specialcharacteristics. In a heap data structure, nodes are arranged based on their values.
Every Heap data structure has the following properties.
1. ORDERING: Nodes must be arranged in a order according to values based on max heap or
minheap.
2. STRUCTURAL: All levels in a heap must be full, except last level and nodes must be filled
fromleft to right strictly.
A binary heap is a complete binary tree which satisfies the heap ordering property. The
ordering can be one of two types:
Min-heap
The value of each node is greater than or equal to the value of its parent, with the
minimum-value element at the root.
2. Max-heap
The value of each node is less than or equal to the value of its parent, with the maximum- value
element at the root.

MAX-HEAP:
Max-Heap is a specialized full binary tree in which every parent node contains greater value
or equal value than its child nodes. In Max heap, the value of the root node is greater than or equal
to either of its children.

Above tree is satisfying both ordering property and structural property according to the
Max-Heap datastructure.
The following operations are performed in Max-Heap data structure:
1. Finding maximum
2. Insertion
3. Deletion
Insertion operation in Max-Heap:
Step-1: Insert the new node as last leaf from
left to rightStep-2: Compare new node with
its parent node.
Step-3: If new node value is greater than its parent node value then swap both values. Step-4:
repeat step-2 and step-3 until new node value is less than its parent node or new node reached
root.

MIN-HEAP:
Min-Heap tree is a specialized full binary tree in which every parent node contains less value
or equal value than its child nodes. In Min-Heap tree, value of the root node is less than or equal
to either of its children.

The following operations are performed on Min-Heap data structure.


1. Finding the minimum
2. Insertion
3. Deletion
Insertion operation in Min-Heap:
Step-1: Insert the new node as last leaf from left to right Step-2:
Compare new node with its parent node.
Step-3: If new node value is less than its parent node value then swap both values.
Step-4: repeat step-2 and step-3 until new node value is greater than its parent node or new node
reached root.

Lab programs

Binary Tree and its traversals

#include<stdlib.h>
#include<stdio.h>
struct bin_tree
{
int data;
struct bin_tree * right, * left;
};
typedef struct bin_tree node; void
insert(node ** tree, int val)
{
node *temp = NULL;
if(!(*tree))
{
temp = (node *)malloc(sizeof(node));
temp->left = temp->right = NULL; temp-
>data = val;
*tree = temp; return;
}
if(val < (*tree)->data)
{
insert(&(*tree)->left, val);
}
else if(val > (*tree)->data)
{
insert(&(*tree)->right, val);
}
}
void print_preorder(node * tree)
{
if (tree)
{
printf("%d\n",tree->data); print_preorder(tree->left);
print_preorder(tree->right);
}
}
void print_inorder(node * tree)
{
if (tree)
{
print_inorder(tree->left); printf("%d\n",tree->data);
print_inorder(tree->right);
}
}
void print_postorder(node * tree)
{
if (tree)
{

print_postorder(tree->left); print_postorder(tree-
>right); printf("%d\n",tree->data);
}
}
void deltree(node * tree)
{
if (tree)
{
deltree(tree->left);
deltree(tree->right);
free(tree);
}
}
node* search(node ** tree, int val)
{
if(!(*tree))
{
return NULL;
}
if(val < (*tree)->data)
{
search(&((*tree)->left), val);
}
else if(val > (*tree)->data)
{
search(&((*tree)->right), val);
}
else if(val == (*tree)->data)
{
return *tree;
}
}
void main()
{
node *root; node
*tmp;
//int i;

root = NULL;
/* Inserting nodes into tree */
insert(&root, 9);
insert(&root, 4);
insert(&root, 15);
insert(&root, 6);
insert(&root, 12);
insert(&root, 17);
insert(&root, 2);

/* Printing nodes of tree */ printf("Pre


Order Display\n");
print_preorder(root);

printf("In Order Display\n");


print_inorder(root);

printf("Post Order Display\n"); print_postorder(root);

/* Search node into tree */ tmp


= search(&root, 4);
if (tmp)
{
printf("Searched node=%d\n", tmp->data);
}
else
{
printf("Data Not found in tree.\n");
}

/* Deleting all nodes of tree */ deltree(root);


}
Output

display binary tree in pre-order, in-order and post-order forms.

Pre Order Display 9


4
2
6
15
12
17
In Order Display 2
4
6
9
12
15
17
Post Order Display 2
6
4
12
17
15
9
Searched node=4

You might also like