troubleshooting Question

BST insertion C code

Avatar of xiromdim
xiromdimFlag for Greece asked on
CAlgorithms
8 Comments1 Solution603 ViewsLast Modified:
where is the mistake in the code below?
#include<stdio.h>
#include<stdlib.h>

struct node{
       int val;
       struct node* left;
       struct node* right;
};
typedef struct node* Tree;
void insert(Tree *root,int x){
     
     if (*root==NULL){
                     *root = (struct node*)malloc(sizeof(struct node));
                     (*root)->val=x;
                     (*root)->left=(*root)->right=NULL;
                     return;
                     }
     if (x<(*root)->val) *root=(*root)->left;
     else if (x>(*root)->val)   *root=(*root)->right;
}
void inorder(Tree root){
     
     if (root==NULL) return;
     inorder(root->left);
     printf("%d ",root->val);
     inorder(root->right);
}

int main(){
    Tree root=NULL;
    
    insert(&root,10);
    insert(&root,5);
    insert(&root,1);
    insert(&root,12);
    inorder(root);
    getchar();
    
    return 0;
}
ASKER CERTIFIED SOLUTION
evilrix
Senior Software Engineer (Avast)

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 8 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 8 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros