Share on Google+Share on Google+

Tree data structure

Advertisement
This tutorial define tree data structure and display how to make a tree.

Description:

A tree data structure that are based on hierarchical tree structure with sets of nodes. A tree is a acyclic connected graph with zero or more children nodes and at most one parent nodes.

Code:

#include <stdio.h>
#include <stdlib.h>
struct node
{
  int data;
  struct node *lchild, *rchild;
};

struct node *insertN(struct node *p,int val)
{
   struct node *temp1,*temp2;
	if(p == NULL)
	{
		p = (struct node *) malloc(sizeof(struct node));
		if(p == NULL)
		  {
	printf("Cannot allocate memory\n");
	exit(0);
        }
	  p->data = val;
	  p->lchild=p->rchild=NULL;
 }
else
{
 temp1 = p;

while(temp1 != NULL)
{
  temp2 = temp1;
  if( temp1 ->data > val)
		 temp1 = temp1->lchild;
  else
		 temp1 = temp1->rchild;
}
if( temp2->data > val)
{
temp2->lchild = (struct node*)malloc(sizeof(struct node));
	temp2 = temp2->lchild;
   if(temp2 == NULL)
        {
	printf("Cannot allocate memory\n");
	exit(0);
        }
   temp2->data = val;
   temp2->lchild=temp2->rchild = NULL;
}
else
{
	temp2->rchild = (struct node*)malloc(sizeof(struct node));
	temp2 = temp2->rchild;
	if(temp2 == NULL)
        {
	printf("Cannot allocate memory\n");
	exit(0);
        }
	temp2->data = val;
	temp2->lchild=temp2->rchild = NULL;
}
}
return(p);
}

void display(struct node *p)
    {
		 if(p != NULL)
         {
			  display(p->lchild);
			  printf("%d\t",p->data);
			  display(p->rchild);
          }
	 }
void main()
{
  struct node *root = NULL;
  int n,x;
  printf("Enter the number of nodes for tree\n");
  scanf("%d",&n);
  while( n -- > 0)
    {
		 printf("Enter the data value\n");
		 scanf("%d",&x);
		 root = insertN(root,x);
   }
	 display(root);
  }

Output:

Download this code

Advertisements

Posted on: June 19, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.