i was trying to do tree traversal.(per-order,in-order,and post-order) here is my code.
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* left;
struct node* right;
};
void Insert(struct node* root,int item)
{
struct node* parent;
struct node* NewNode = (struct node*)malloc(sizeof(struct node));
NewNode->left = NULL;
NewNode->data = item;
NewNode->right = NULL;
if (root == NULL)
root = NewNode;
else
{
parent = root;
while (1)
{
if (parent->data>item)
{
if(parent->left == NULL)
{
parent->left = NewNode;
return;
}
parent = parent->left;
}
if (parent->data<item)
{
if(parent->right == NULL)
{
parent->right = NewNode;
return;
}
parent = parent->right;
}
}
}
}
void pre(struct node *newNode)
{
if(newNode!=NULL)
{
printf("%d ",newNode->data);
pre(newNode->left);
pre(newNode->right);
}
}
void in(struct node *newNode)
{
if(newNode!=NULL)
{
in(newNode->left);
printf("%d ",newNode->data);
in(newNode->right);
}
}
void post(struct node *newNode)
{
if(newNode!=NULL)
{
post(newNode->left);
post(newNode->right);
printf("%d ",newNode->data);
}
}
int main(void)
{
int num,i;
printf("\nHow many Numbers you wanna Enter in tree:\t");
scanf("%d",&num);
int numArr[num];
printf("\nEnter the numbers: \n");
struct node* root = NULL;
for (i=0;i<num;i++)
{
scanf("%d",&numArr[i]);
Insert(root,numArr[i]);
}
printf("\nPre order traversal is:\n");
pre(root);
printf("\nIn order traversal is:\n");
in(root);
printf("\nPost order traversal is:\n");
post(root);
}
i think i have problem with inserting the value because when i run the code the output is just empty. could anyone explain me where m i going wrong?
at insert function m taking the root node and the item to be inserted as argument.
then i'm creating a new node using malloc.
inserting data to the new node and left, right is null as left and right is currently not pointing to any nodes.
then checking if root is null or not. if it is null m assigning the new node to root node.
if root is not null. (i should not loose the root so i am copying root to parent and using that.)
m checking if the data is less than root or not. if it is less m going to the left of root if left of root is null m inserting the address of new node there if it is not null m just going left and left until it becomes null.
m doing the same thing(just going right) if data is greater than the value in root.
my explanation tells me m going on the right path. but my code tell me a different story.