Untitled
unknown
plain_text
4 years ago
2.5 kB
9
Indexable
#include<stdio.h>
#include<stdlib.h>
void insert(int *t, int key);
void preorder(int *t, int i);
int check(int *t, int i);
int main()
{
int t[100];
int i, ch, num, k;
for(i = 0; i<100; i++)
{
t[i] = -1;
}
while(1)
{
printf("\n1. Insert\n2. Traverse\n3. Check\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1: printf("\nEnter the number to insert: ");
scanf("%d", &num);
insert(t,num);
break;
case 2: printf("Tree elements in preorder is: ");
preorder(t,0);
break;
case 3: k = check(t,0);
if(k == 0)
{
printf("\nIt is not a binary search tree\n");
}
else
{
printf("\nIt is a binary search tree\n");
}
break;
case 4: exit(0);
}
}
}
void insert(int *t, int key)
{
int i = 0;
while(t[i] != -1)
{
if(key < t[i])
{
i = 2*i + 1;
}
else
{
i = 2*i + 2;
}
}
t[i] = key;
}
void preorder(int *t, int i)
{
if(t[i] != -1)
{
printf("%d - ", t[i]);
preorder(t, 2*i + 1);
preorder(t, 2*i + 2);
}
}
int check(int *t, int i)
{
int n;
if(t[i] != -1)
{
if(t[2*i + 2] == -1)
{
check(t, 2*i + 1);
}
else if(t[2*i + 1] < t[i] && t[2*i + 2] > t[i])
{
check(t, 2*i + 1);
check(t, 2*i + 2);
}
else
{
return 0;
}
}
else
{
return 1;
}
}
Editor is loading...