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;
}

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.

@Narue

Ok.i have marked it as Solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.