Friday 27 March 2015

Program to implement tree using linked list in C 

We will be using the linked list to connect the different nodes of the tree recursively and using preorder traversal to print the vertices of the tree

The sample tree used is :








The above figure shows the binary tree, however build any tree using the approach laid out in the program 

#include<stdio.h>
#include<stdlib.h>
struct Tree
{
int key;
struct Tree* left;
struct Tree *right;
}*root=NULL;
void displaytree(struct Tree *);
int main()
{
struct Tree *temp;
temp=(struct Tree *)malloc(sizeof(struct Tree));
temp->key=5;
root=temp;
temp=(struct Tree *)malloc(sizeof(struct Tree));
temp->key=6;
root->left=temp;
temp=(struct Tree *)malloc(sizeof(struct Tree));
temp->key=7;
temp->left=NULL;
temp->right=NULL;
root->right=temp;
temp=(struct Tree *)malloc(sizeof(struct Tree));
temp->key=8;
temp->left=NULL;
temp->right=NULL;
root->left->left=temp;
temp=(struct Tree *)malloc(sizeof(struct Tree));
temp->key=9;
temp->left=NULL;
temp->right=NULL;
root->left->right=temp;
displaytree(root);
return 0;
}
void displaytree(struct Tree *node)
{
    if(node==NULL)
        return;
printf("key=%d",node->key);
displaytree(node->left);
displaytree(node->right);
}

Output:


1 comment:

  1. How to make a function which uses loop to insert element in the tree ?

    ReplyDelete