c++treebinary-treeinsertion

Level order insertion in binary tree


We have to insert elements in a binary tree level-by-level, that is, for an array:

a = {1,2,3,4,5,6}

1st level = [1]
2nd level = [2, 3]
3rd level = [4, 5, 6]

I have worked out a code but it results in NULL tree every time.

struct node
{
    int data;
    struct node* left;
    struct node* right;
};

node* create(int x)
{
    node* tmp;
    tmp=(struct node *)malloc(sizeof(struct node));
    tmp->data=x;
    tmp->left=NULL;
    tmp->right=NULL;
    return tmp;
}

struct node* tree;

void insert(struct node* tree, int* a, int start, int n)
{
    int left =2*start+1;
    int right=2*start+2;
    if(left>n || right>n)
        return;
    if(tree==NULL)
    {
        tree=create(a[start]);
    }
    if(tree->left==NULL && tree->right==NULL)
    {
        if(left<n)
            tree->left=create(a[left]);
        if(right<n)
            tree->right=create(a[right]);
    }
    insert(tree->left,a,left,n);
    insert(tree->right,a,right,n);
}

Solution

  • You're passing tree by value; whoever calls insert still has a NULL pointer after insert returns. See What's the difference between passing by reference vs. passing by value? for some background.