0

Hello.

im having a small problem creating a tree. im not sure where im going wrong.
Can anyone please help? Thanks.

Here is the code:

#include <stdio.h>
#include <stdlib.h>

struct tree_el {
   int val;
   struct tree_el *right; 
   struct tree_el *left;
};

typedef struct tree_el node;

void printout(node *tree) 
{
   if (tree -> left) 
	   printout(tree->left);
   
   printf("%d\n",tree->val);
   
   if (tree -> right)
	   printout(tree->right);
}


void insert(node *parent, node *child)
{
	if (parent == NULL) {
		parent = child;
		return;
	} 
	if (child -> val < parent -> val) {
		insert(parent -> left, child);
	} else {
		insert(parent -> right, child);
	}
}

int main(void)
{
   node *curr, *root;
   int i;

   root = NULL;

   for (i = 1; i <= 10; i++) {
      /* Allocate memory */
      curr = (node *)malloc(sizeof(node));

      curr->left = curr->right = NULL;
      curr->val = i;

	  /* Insert the node */
      insert(root, curr);
   }

   printout(root);
   getchar();

   return 0;
}
2
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by myk45
0

Please don't create a new thread with the same question. Cross posting is just as bad as posting in the wrong place (if not worse). Instead, flag your own thread as bad with the note "this belongs in so and so forum, please move it" for the moderators. Then they can clean up your mess.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.