Tree – Insert an element into a tree in c++

Simple program to insert an element into a tree, I wrote in c++:
#include
#include
#include
// Define the variables used to store the data
// Use struct, or also you can use arrays to store values into a tree.
// use a struct if you dont know how many elements you would be
// storing into the tree.
struct node
{
int info;
struct node *llink;
struct node *rlink;
};
typedef struct node* NODE;
// value to assign the memory needed
NODE getnode()
{
NODE x;
x = (NODE)malloc(sizeof(struct node));
if(x==NULL)
{
printf(“out of memoryn”);
exit(0);
}
return x;
}
NODE insert(int item, NODE root)
{
char direction[10];
printf(“Enter the directions”);
scanf(“%s”, direction);
NODE temp;
NODE cur;
NODE prev;
temp = getnode();
temp->info = item;
temp->llink = temp->rlink = NULL;
if(root == NULL) return temp;
prev = NULL;
cur = root;
int i=0;
for(i=0;illink;
else
cur = cur->rlink;
}
if(cur != NULL || i!=strlen(direction))
{
printf(“Insertion Fail”);
//free the memory you allocated. freenode(temp);
return root;
}
if(direction[i-1] == ‘l’)
prev->llink = temp;
else
prev->rlink = temp;
return root;
}
int main()
{
NODE temp;
int item;
NODE root;
insert(1, root);
char c;
do {
c=getchar();
putchar (c);
} while (c != ‘.’);
return 0;
return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *