Thread: Problem in creating binary tree

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    103

    Problem in creating binary tree

    Hi All

    I am trying to create Binary tree from array elements but when I tried to run this program, it was giving segementation fault error.

    The code is as follow:
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    struct node 
    {
    
     struct node *left;
     struct node *right;
    
    int data;
    };
    
    void insert(struct node **p,int num) {
    
    if ( *p == NULL )
    {
      
      (*p) = (node *)malloc(sizeof(struct node));
      (*p)->left = NULL;
      (*p)->right = NULL;
      (*p)->data = num; 
    }
    else
    {
      if( num == (*p)->data)
         return;
    }
    
    if ( num < (*p)->data)
    insert(&((*p)->left),num);
    else
    insert(&((*p)->right),num);
    }
    
    
    void createBinary(struct node *ptr,int a[],int i)
    {
      int m;
       
      for ( m = 0;m< i; m++ )
      {
    
       insert( &ptr,a[m]);
       
      }  
    }
    
    int main()
    {
      int a[] = {11,12,13,14,15};
      int size1 =0;
      struct node *ptr = NULL;
    
    
      size1=sizeof(a) / 4;
            
      createBinary(ptr,a,size1);
     }
    Could any body help me where is the problem.


    Thanks

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > createBinary(ptr,a,size1);
    ...
    > insert( &ptr,a[m]);

    You're not updating your pointer.
    Only the copy of it inside the function.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    And
    size1=sizeof(a) / 4;
    change it to
    size_t size1 = sizeof(a) / sizeof(a[0]);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. searching and insertion in a binary search tree
    By galmca in forum C Programming
    Replies: 1
    Last Post: 03-26-2005, 05:15 PM
  2. Binary Search Tree, Inserting node
    By cheryl_li in forum C Programming
    Replies: 1
    Last Post: 09-13-2003, 03:53 AM
  3. Problem with binary search tree :(
    By Unregistered in forum C Programming
    Replies: 10
    Last Post: 05-01-2002, 10:31 PM
  4. problem in binary expression tree
    By hanij in forum C Programming
    Replies: 6
    Last Post: 04-28-2002, 08:31 AM
  5. binary tree node structure
    By Kirsten in forum C Programming
    Replies: 2
    Last Post: 04-26-2002, 08:02 PM