insert operation is not happening for BST.can cause?-1 is null element in array. Linked list is not be for this code.
void insert(int *Tree,int element)
{
int temp=0;/* first subscript*/
if(Tree[temp]==-1){
Tree[temp]=element;
return;
}
while(1){
if((Tree[temp]>element))
if (Tree[2*temp+1]==-1){
Tree[2*temp+1]==element;
break;
}
else
temp=2*temp+1;
else if(Tree[2*temp+2]==-1){
Tree[2*temp+2]==element;
break;
}
else
temp=2*temp+2;
}
}
Fixing the indentation, adding braces, and the replacing the == used for assignment (should be =), your code works OK-ish. Still would like to add a check to make sure you don't exceed the size of tree...
#include <stdio.h>
void insert(int *Tree,int element)
{
int temp=0;/* first subscript*/
if(Tree[temp]==-1){
Tree[temp]=element;
return;
}
while(1)
{
if((Tree[temp]>element))
{
if (Tree[2*temp+1]==-1)
{
Tree[2*temp+1]=element;
break;
}
else
{
temp=2*temp+1;
}
}
else
{
if(Tree[2*temp+2]==-1)
{
Tree[2*temp+2]=element;
break;
}
else
{
temp=2*temp+2;
}
}
}
}
int main(void) {
int tree[100];
int ii;
for(ii=0;ii<100;ii++) tree[ii]=-1;
insert(tree, 5);
insert(tree, 3);
insert(tree, 9);
insert(tree, 4);
for(ii=0; ii<10; ii++) printf("%d: %d\n", ii, tree[ii]);
}
Whether this actually produces the tree you are looking for is something I cannot guess.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With