DS – BST Insertion using Recursion

First Node Insertion:

Second Insertion:

#include<stdio.h>
#include<stdlib.h>
 
struct Node
{
            int data;
            struct Node *left;
            struct Node *right;     
};
struct Node *root = NULL;
struct Node* new_node(int);
void print_inorder();
void inorder(struct Node*);
struct Node* insert(struct Node*, int);
int main()
{
            int ch, ele;
            while(1)
            {
                        printf(“1. Insert \n”);
                        printf(“2. Inorder \n”);
                        printf(“3. Quit \n”);
                        printf(“Enter choice : “);
                        scanf(“%d”, &ch);
                        switch(ch){
                                    case 1  :           printf(“Enter element : “);
                                                            scanf(“%d” , &ele);      
                                                            root = insert(root , ele);
                                                            break;
                                   
                                    case 2 :           print_inorder();
                                                            break;
                                   
                                    case 3  :           exit(1);
                                    default :           printf(“Invalid Choice \n\n”);
                                   
                        }
            }
            return 0;          
}
struct Node* insert(struct Node* node, int ele){
            if(node==NULL){
                        return new_node(ele);
            }
            if(ele < node->data){
                        node->left = insert(node->left , ele);  
            }
            if(ele > node->data){
                        node->right = insert(node->right , ele);         
            }
            return node;
}
 
struct Node* new_node(int data){
            struct Node* node;     
            node = (struct Node*)malloc(sizeof(struct Node));
            node->data = data;
            node->left = NULL;
            node->right = NULL;
            return node;
}
 
void print_inorder(){
            if(root==NULL){
                        printf(“BST is empty \n\n”);
            }
            else{
                        inorder(root);
                        printf(“\n\n”);
            }
}
 
void inorder(struct Node* node){
            if(node->left){
                        inorder(node->left);
            }
            printf(“%d \t”, node->data);
            if(node->right){
                        inorder(node->right);
            }
}
Scroll to Top