Insert a node in a binary tree - Convert iterative to recursive

Viewed 268

Repeated Question:

Recently I'm reading Data Structure(Binary Search Trees), I understand recursion very well and can trace it as well.

I used an approach which always worked for me i.e write a program with a loop, then eliminate loop and write a recursive function, the base condition will be same as loop exit condition.

But when it comes to writing one without my loop method, am getting failed. I wasn't able to write a recursive function to insert a node in Binary Search Tree.(Though I understood it properly by referring the solution).

Kindly guide me, How to improve it?

#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node *left;//To store the address of the left child
    struct node *right;//To store the address of the Right child
};
struct node * root;
struct node *createnewnode(int x)
{
    struct node *n=(struct node *)malloc(sizeof(struct node));
    n->data=x;
    n->left=NULL;
    n->right=NULL;
    return n;
}
void Insert(int x)
{
    struct node *a,*b;
    struct node *temp=root;
    if(root==NULL)
        root=createnewnode(x);
    else
    {
        while(1)
         {
            if(x<=temp->data)
              {
                 if(temp->left!=NULL)
                    temp=temp->left;
                 else
                 {
                   a=createnewnode(x);
                   temp->left=a;
                   break;   
                 }
              }
            else
              {
                if(temp->right!=NULL)
                    temp=temp->right;
                 else
                 {
                   a=createnewnode(x);
                   temp->right=a;
                   break;   
                 }
              }  
         }
    }

}
int main()
{
    root==NULL;//Empty Tree
    Insert(15);
    Insert(10);
    Insert(20);
    Insert(25);
    return 0;
}

Edit: Sorry for not posting the code previously. This is the code I have written for inserting a node, now how do I convert this into a recursive method?

1 Answers
Related