/*Write a C program to create a tree. */
#include
#include
#include
typedef struct TREE
{
struct TREE *left_child;
int element;
struct TREE *right_child;
} TREE;
TREE *CreateTree (int element, TREE *tree_ptr)
{
/* if tree is null, the following code create the parent node.*/
if (! tree _ptr)
{
tree_ptr= (TREE *) malloc (sizeof (TREE));
tree_ptr->element=element;
tree_ptr->left_child=NULL;
tree_ptr->right_child=NULL;
return (tree_ptr);
}
/* if tree is not null. */
if (elementelement) //left child.
tree_ptr->left_child=CreateTree (element, tree_ptr->left_child);
else
if (element>tree_ptr->element) //right child.
tree_ptr->right_child=CreateTree (element, tree_ptr->right_child);
return (tree_ptr);
}
void Display_Tree (int height, TREE *tree)
{
int i;
if (tree)
{
Display_Tree (height+1, tree->right_child);
printf ("\n");
for (i=0; i
printf (" ");
printf ("%d", tree->element);
Display_Tree (height+1, tree->left_child);
}
}
void main ()
{
int x;
TREE *tree=NULL;
clrscr ();
while (1)
{
printf ("\n Enter new element (1000 for exist) :");
scanf ("%d", &x);
if (x = = 1000)
break;
tree = CreateTree(x, tree);
printf ("\n\n The tree is: \n");
Display_Tree (1, tree);
}
}
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment