B
Bill Cunningham
I copied this code from a binary tree site just for C. It's somewhat
easier to understand. Somewhere strange looking too. I had to change main's
return type from void to int. The author had main's return as void.
#include<stdlib.h>
#include<stdio.h>
struct tree_el {
int val;
struct tree_el *right, *left;
};
typedef struct tree_el node;
void insert(node ** tree, node * item)
/* Why is tree a ** ? */
{
if (!(*tree)) {
/* I am guessing that (*tree) is a dereference occuring before the if !
statement */
*tree = item;
return;
}
if (item->val < (*tree)->val)
insert(&(*tree)->left, item);
/* is insert being changed to point to a dereferenced tree here */
else if (item->val > (*tree)->val)
insert(&(*tree)->right, item);
/* Same thing again */
}
void printout(node * tree)
{
if (tree->left)
printout(tree->left);
printf("%d\n", tree->val);
if (tree->right)
printout(tree->right);
}
int main()
{
node *curr, *root;
int i;
root = NULL;
for (i = 1; i <= 10; i++) {
curr = (node *) malloc(sizeof(node));
curr->left = curr->right = NULL;
curr->val = rand();
insert(&root, curr);
}
printout(root);
}
easier to understand. Somewhere strange looking too. I had to change main's
return type from void to int. The author had main's return as void.
#include<stdlib.h>
#include<stdio.h>
struct tree_el {
int val;
struct tree_el *right, *left;
};
typedef struct tree_el node;
void insert(node ** tree, node * item)
/* Why is tree a ** ? */
{
if (!(*tree)) {
/* I am guessing that (*tree) is a dereference occuring before the if !
statement */
*tree = item;
return;
}
if (item->val < (*tree)->val)
insert(&(*tree)->left, item);
/* is insert being changed to point to a dereferenced tree here */
else if (item->val > (*tree)->val)
insert(&(*tree)->right, item);
/* Same thing again */
}
void printout(node * tree)
{
if (tree->left)
printout(tree->left);
printf("%d\n", tree->val);
if (tree->right)
printout(tree->right);
}
int main()
{
node *curr, *root;
int i;
root = NULL;
for (i = 1; i <= 10; i++) {
curr = (node *) malloc(sizeof(node));
curr->left = curr->right = NULL;
curr->val = rand();
insert(&root, curr);
}
printout(root);
}