#define _GNU_SOURCE #include #include #include struct Tree { int elem; struct Tree *left; struct Tree *right; }; /* displays tree recursively */ void display (struct Tree *tree) { if (tree) { display (tree->left); printf ("The next element is %d\n", tree->elem); display (tree->right); } } /* inserts element into tree recursively */ struct Tree * insert (struct Tree *tree, int elem) { if (tree == NULL) { /* new element */ tree = malloc (sizeof (struct Tree)); tree->elem = elem; } if (elem < tree->elem) { /* insert into left branch */ tree = insert (tree->left, elem); } else /* insert on the right */ tree = insert (tree->right, elem); return tree; } int main (int argc, char **argv) { int result; int elem; char *line = NULL; int length; struct Tree *tree = NULL; while (getline (&line, &length, stdin) > 1) { /* parse next line */ /* pass over white space */ while (line && isspace(line)) { line++; } /* read next integer */ result = sscanf (line, "%d", elem); while (result != EOF) { if (result == 0) { fprintf (stderr, "Non-integer found, aborting !\n"); exit (1); } /* skip integer just read */ while (line && !isspace(line)) { line++; } /* insert element into tree */ insert (tree, elem); while (line && isspace(line)) { line++; } result = sscanf (line, "%d", elem); } line = NULL; display (tree); tree = NULL; } return (0); }