Hey at the moment my loop is just giving infinite amounts of 0's but it is meant to give me 0 1 2 3 4 5 6... I'm not sure what I've done wrong so any help would be great.
[code]
#include #include /* Small program to explore using binary trees.
The program takes an array filled with random numbers
and inserts the numbers into a binary tree.
The program then prints the contents of the tree in
key order. It should print -
0 1 2 3 4 5 6 7 8 9
The program then free's up the tree.
*/
struct treeRecord
{
int key;
struct treeRecord *left, *right;
};
typedef struct treeRecord treeNode;
void insertArrayInTree(treeNode **root, int array[], int size);
void insertElementInTree(treeNode **root, int number);
void printTree(treeNode *start);
void freeTree(treeNode **start);
treeNode* newNode(int number);
int main()
{
int array[] = { 6, 3, 8, 1, 5, 2, 9, 7, 4, 0 };
treeNode *root = NULL;
insertArrayInTree(&root, array, 10);
printTree(root);
printf("
");
freeTree(&root);
return 0;
}
void insertArrayInTree(treeNode **root, int array[], int size)
{
/* insert elements of array into correct position in binary tree */
int i;
for (i=0; ikey)
insertElementInTree(&temp->left, number);
else
insertElementInTree(&temp->right, number);
}
}
void printTree(treeNode *root)
{
/* print the contents of the tree in order */
while (root != NULL)
{
printTree(root->left);
printf(" %d", root->key);
printTree(root->right);
}
}
void freeTree(treeNode **root)
{
/* free up memory allocated to binary tree */
treeNode *temp = *root;
if (temp != NULL)
{
if (temp->left != NULL) freeTree(&temp->left);
if (temp->right != NULL) freeTree(&temp->right);
free(temp);
*root = NULL;
}
}
treeNode* newNode(int number)
{
/* dynamicaly allocate memory for a treeNode
make sure it is initialised correctly
*/
treeNode *temp;
temp = (treeNode *) malloc(sizeof(treeNode));
if (temp == NULL)
{
printf("WARNING - Memory allocation error
");
exit(EXIT_FAILURE);
}
temp->key = number;
temp->left = NULL;
temp->right = NULL;
return temp;
}
[/code]
Comments
Correct version (with less recursive calls):
[code]void printTree(treeNode *root)
{
/* print the contents of the tree in order */
if(root != NULL)
{
if(root->left != NULL)
{
printTree(root->left);
}
printf("%d ", root->key);
if(root->right != NULL)
{
printTree(root->right);
}
}
}
[/code]