Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary search tree insertion in c [closed]

Tags:

c

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;
    }
}
like image 987
YavuzGiran Avatar asked Mar 16 '26 12:03

YavuzGiran


1 Answers

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.

like image 163
Floris Avatar answered Mar 18 '26 02:03

Floris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!