I have done experiments with tree algorithms in C. To check their accuracy, I implemented a simple function to create random binary trees. It somehow seems that all generated trees are regular, which means that the tree is "full" and has exactly (2 ^ height) -1 nodes.

I start at the root node and call the function recursively for left and right child with a certain probability. The function also has a depth limit. The created tree does not always have the full height, but is always regular. I suspect something is wrong with my random number generator.

`#include `
#include
#include
/ * Tree node; Data omitted for brevity * /
Typedef structure node {
Structure node * left, * right;
} Nodes;
/ * simple utility for printing a tree * /
void _print_tree (node * node, int lvl) {
if (! node) return;
for (int i = 0; iright, lvl + 1);
for (int i = 0; iright, lvl + 1);
}
void print_tree (Node * root) {
_print_tree (root, 0);
}
/ * Create a random tree with a certain probability to create a child
Node and specified maximum depth / height of the tree * /
Node * make_random_tree (double prob, int maxdepth) {
Node * root = NULL;
if (maxdepth--)
root = calloc (1, sizeof (Node));
if (root) {
if (rand () < (double) RAND_MAX * prob)
root->left = make_random_tree (prob, maxdepth);
if (rand () < (double) RAND_MAX * prob)
root->right = make_random_tree (prob, maxdepth);
}
Return root;
}
int main (int argc, char * argv.)[]) {
Double sample = 0.5;
int maxdepth = 20;
if (argc> 1) {
char * ep;
prob = strtod (argv[1], & ep);
return if (* ep) 1;
}
if (argc> 2) {
char * ep;
maxdepth = strtol (argv[2]& ep, 10);
return if (* ep) 1;
}
/ * Random Number Generator Initializes Properly?! * /
struct timeval tv;
gettimeofday (& tv, NULL);
unsigned int seed = tv.tv_sec ^ tv.tv_usec;
Srand (seeds);
Node * tree = make_random_tree (prob, maxdepth);
print_tree (tree);
}