Binary Search Tree and all traversals
#include <stdio.h>
#include <stdlib.h>
struct node {
int key;
struct node *left, *right;
};
struct node* newNode(int item)
{
struct node* temp
= (struct node*)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
void inorder(struct node* root)
{
if (root != NULL) {
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
void preorder(struct node* root)
{
if (root != NULL) {
printf("%d ", root->key);
preorder(root->left);
preorder(root->right);
}
}
void postorder(struct node* root)
{
if (root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%d ", root->key);
}
}
struct node* insert(struct node* node, int key)
{
if (node == NULL)
return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
return node;
}
int main()
{
struct node* root = NULL;
int choice=1,val;
printf("Enter the value to be inserted : ");
scanf("%d",&val);
root = insert(root,val);
while(choice==1){
printf("Want another value to be inserted(1/0) : ");
scanf("%d",&choice);
if(choice==1)
{
printf("Enter the value : ");
scanf("%d",&val);
insert(root,val);
}
}
printf("\nThe inorder traversal is : \n");
inorder(root);
printf("\nThe preorder traversal is : \n");
preorder(root);
printf("\nThe postorder traversal is : \n");
postorder(root);
return 0;
}
Comments
Post a Comment