Program to create and traverse binary tree
#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node *leftChild;
struct node *rightChild;
int data;
};
struct node *root;
int leftChild(struct node *tree) // Function to confirm creating left child
{
char choice;
printf("Do you want to enter a left Child(y/n)");
scanf("%d", &choice);
if(choice == 'y')
return 1;
else
return 0;
}
int rightChild(struct node *tree) // Function to confirm creating right child
{
char choice;
printf("Do you want to enter a right Child(y/n)");
scanf("%d", &choice);
if(choice == 'y')
return 1;
else
return 0;
}
void create(struct node *tree)
{
if(leftChild(tree))
{
tree->leftChild = (struct node*)malloc(sizeof(struct node));
printf("Enter the data for left child: ");
scanf("%d", &tree->leftChild->data);
create(tree->leftChild);
}
else
{
tree->leftChild = NULL;
}
if(rightChild(tree))
{
tree->rightChild = (struct node*)malloc(sizeof(struct node));
printf("Enter the data for right child: ");
scanf("%d", &tree->rightChild->data);
create(tree->rightChild);
}
else
{
tree->rightChild = NULL;
}
}
void inorder(struct node *tree)
{
if(tree != NULL)
{
inorder(tree->leftChild);
printf("%d", tree->data);
inorder(tree->rightChild);
}
}
void preorder(struct node *tree)
{
if(tree != NULL)
{
printf("%d", tree->data);
preorder(tree->leftChild);
preorder(tree->rightChild);
}
}
void postorder(struct node *tree)
{
if(tree != NULL)
{
postorder(tree->leftChild);
postorder(tree->rightChild);
printf("%d", tree->data);
}
}
int main()
{
printf("Creating the root\n");
root = (struct node*)malloc(sizeof(struct node));
printf("Enter the data for root: ");
scanf("%d", &root->data);
create(root);
printf("Inorder traversal for the tree is\n");
inorder(root);
printf("Preorder traversal for the tree is\n");
preorder(root);
printf("Postorder traversal for the tree is\n");
postorder(root);
return 0;
}