Thread: Binary tree program is not working

  1. #1
    Registered User
    Join Date
    Aug 2015
    Posts
    73

    Binary tree program is not working

    i am trying to write binary tree program in c.
    but its not printing the values. and it is not coming out of while loop.
    this is the code i tried

    Code:
    #include <stdio.h>#include <stdlib.h>
    
    
    typedef struct node {
        int data;
        struct  node* left;
        struct node* right;
    }node;
    
    
    int n;
    
    
    int main()
    {
        node *root, *first, *current, *temp; int num,i;
        printf("How many no.\n");
        scanf("%d", &n);
        root=(node*)malloc(sizeof(node));
        first = root;
        printf("Enter no.");
        scanf("%d", &root->data);
        for(i=1;i<n;i++) {
            current=first;
            temp = (node*)malloc(sizeof(node));
            printf("Enter no.");
            scanf("%d", &num);
            temp->data=num;
            if(num<current->data) {
                current->left=temp;
            }
            else current->right=temp;
    
    
        first=current;
    
    
        }
        temp->left=NULL;
        temp->right=NULL;
        
        current=root;
        while(current->left!=NULL || current->right!=NULL) {
            printf("%d\n", current->data);
            current=current->left;
        }
        return 0;
    }
    this code is printing infinte garbage values. can anyone tell me how write program to implement binary tree?

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    3,688
    Step 1: Learn how to write a function other than main.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    Registered User
    Join Date
    Aug 2015
    Posts
    73
    i can convert code to function but the problem is in while loop. why its printing garbage values infinitely?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 04-16-2011, 04:44 AM
  2. Problem with binary tree program
    By rsk8332 in forum C++ Programming
    Replies: 3
    Last Post: 04-09-2008, 07:08 PM
  3. Replies: 2
    Last Post: 08-01-2007, 01:08 PM
  4. display tree data in binary tree format
    By xddxogm3 in forum C++ Programming
    Replies: 4
    Last Post: 12-11-2003, 12:47 AM
  5. How to program a data tree? (not binary)
    By Captain Penguin in forum C++ Programming
    Replies: 5
    Last Post: 12-30-2002, 03:25 PM

Tags for this Thread