简体   繁体   中英

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

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 ie 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?

The recursive Insert always asks the following question: can I insert a node in the current root ? If not because root is not null then I have to check whether I have to recurse on the left or right subtree and call Insert recursively.

Something like the following should be enough to give you an idea on how to do it

Node* Insert(Node* root, int x) {
  if (root == NULL)
    return createnewnode(x);
  else 
    if (x <= root->data) 
      root->left=Insert(root->left);
    else
      root->right=Insert(root->right);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM