vendredi 29 mai 2015

Print all the unique elements of an array

I am trying to print all the unique elements of a given array using a binary search tree.

What I am doing:

  1. Input all the numbers in an array.
  2. Search for each element of the array one by one in the bst,
    • if (an element is not found in the bst)
      • put it there and print it
    • else
      • go to the next element
#include<stdlib.h>
#include<stdio.h>

struct node
{   
    int data;
    struct node* left;
    struct node* right;
} *root = NULL;

void insert(struct node *n, int value)
{
    if (n == NULL)
    {
        n = (struct node*)malloc(sizeof(struct node));
        n->data = value;
        n->left = NULL;
        n->right = NULL;
        printf("%d ", value);
        return;
    }

    if ((n->data) == value)
        return;
    if ((n->data) > value)
        insert(n->left, value);
    else
        insert(n->right, value);
}   

int main()
{
    int a[100], i, n;
    printf("Enter the number of elements : ");
    scanf("%d",&n);
    for (i = 0; i < n; i++)
        scanf("%d",&a[i]);
    printf("After removal of duplicates, the new list is : \n");
    for (i = 0; i < n; i++)
        insert(root, a[i]);
    printf("\n");
    return 0;
}       

Aucun commentaire:

Enregistrer un commentaire