Professional Documents
Culture Documents
ST
APPLICATIONS (BCA 1 YEAR)
data structure in c
Subject code:
Roll no: 191950040010
Submitted by: SHIVAM PANDEY
Submitted to: SAIDA MAM
Write short note on the following:
1. Tree
A tree is a nonlinear data structure, compared to arrays,
linked lists, stacks and queues which are linear data
structures. A tree can be empty with no nodes or
a tree is a structure consisting of one node called the root
and zero or one or more sub trees.
• Tree is one of the most powerful and advanced data structures.
• it is a non-linear data structure compared to arrays, linked lists,
stack and queue.
•it represents the nodes connected by edges.
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;
}
}
}
printf("\n Binary Search Tree nodes in Inorder
Traversal: ");
inorder(root);
printf("\n");
return 0;
}
Basic Operations
Following are the basic operations of a tree −
• Search − Searches an element in a tree.
• Insert − Inserts an element in a tree.
• Pre-order Traversal − Traverses a tree in a pre-
order manner.
• In-order Traversal − Traverses a tree in an in-order
manner.
• Post-order Traversal − Traverses a tree in a post-
order manner.
Search Operation
while(current->data != data)
{
if(current != NULL)
{
printf("%d ",current->data);
//not found
if(current == NULL)
{
return NULL;
}
}
}
return current;
}
Insert Operation
Algorithm
void insert(int data)
{
struct node *tempNode = (struct node*)
malloc(sizeof(struct node));
struct node *current;
struct node *parent;
tempNode->data = data;
tempNode->leftChild = NULL;
tempNode->rightChild = NULL;
while(1)
{
parent = current;
if(current == NULL)
{
parent->leftChild = tempNode;
return;
}
}
//go to right of the tree
else
{
current = current->rightChild;