Link to home
Start Free TrialLog in
Avatar of dimi67
dimi67Flag for Greece

asked on

binary tree insert C code

where is the error?
#include <stdio.h>
#include<stdlib.h>
 
typedef struct bnode{
        int key;
        struct bnode* left;
        struct bnode* right;
        }BNODE;
 
void printKeysReverse(BNODE* current);
void inorder(BNODE* current);
void insert(BNODE **root,int key);
int main(void){
    BNODE* root=NULL;
    
    insert(&root,27);
    insert(&root,59);
    insert(&root,21);
    insert(&root,38);
    insert(&root,54);
    insert(&root,63);
    insert(&root,8);
    insert(&root,70);
    insert(&root,15);
    
}
void insert(BNODE **root, int val){
  BNODE *newnode;
  
  newnode=(BNODE*)malloc(sizeof(BNODE));        
  newnode->right=NULL;
  newnode->left=NULL;
  
  if ((*root)==NULL){
       *root=newnode;
       (*root)->key=val;              
       return;
       }
  if (val<(*root)->key) insert((&root)->left,val);
  else insert((&root)->right,val);     
}//end 
 
void inorder(BNODE *root){
     
     if (root==NULL) return ;
     inorder(root->left);
     printf("%d ",root->key);
     inorder(root->right);
}//end inorder

Open in new window

Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

What's the symtom?
ASKER CERTIFIED SOLUTION
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The problems specifically were...

I hope this helps.

-Rx.
Before:  if (val<(*root)->key) insert((&root)->left,val);
After: if (val<(*root)->key) insert(&(*root)->left,val);
 
Before:  else insert((&root)->right,val);     
After: else insert(&(*root)->right,val);     

Open in new window

Avatar of dimi67

ASKER

thanks! :-)
Avatar of kollidinesh
kollidinesh

if condition which you have return is wrong

it should be

if (val<(*root)->key))
    insert((&root)->left,val);
else
  insert(&(*root)->left,val);