binary tree?

P

pc_newbie

Simon said:
#include <stdio.h>
#include <stdlib.h>

struct tree {
int value;
struct tree *left;
struct tree *right;
};

struct tree *create(int start, int max)
{
struct tree *new = NULL;

/* If this node should exist: */
if(start < max)
{
/* First, create it: */
new = malloc(sizeof *new);
if(!new)
{
fprintf(stderr, "Error allocating memory\n");
exit(EXIT_FAILURE);
}
new->value = start;

/* Then create its children: */
new->left = create(start * 2, max);
new->right = create(start * 2 + 1, max);
}
return new;
}

Call it with create(1, 8) for your example tree.

C:\prog\c>gcc -std=c99 -pedantic -Wall -W -O2 bftree.c -o bftree

C:\prog\c>bftree 32
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

My tree pretty-printing routine is quite interesting.
Thank you very much :) it works very well
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
474,079
Messages
2,570,575
Members
47,207
Latest member
HelenaCani

Latest Threads

Top