Skip to content

Commit

Permalink
Create binary_traversal.c
Browse files Browse the repository at this point in the history
  • Loading branch information
jithinkc22j authored Oct 22, 2020
1 parent bdcc1c4 commit ac90e3a
Showing 1 changed file with 121 additions and 0 deletions.
121 changes: 121 additions & 0 deletions binary_traversal.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// C program to demonstrate binary search tree with Traversal.
/* Created by Jithin K c */
#include <stdio.h>
#include<stdlib.h>
#include<string.h>

struct node
{

int key;

struct node *left, *right;
};

// function to create a new BST node

struct node *newNode(int item)
{

struct node *temp = (struct node *)malloc(sizeof(struct node));

temp->key = item;

temp->left = temp->right = NULL;

return temp;
}

// function to insert a new node with given key in BST

struct node* insert(struct node* node, int key)
{

// If the tree is empty, return a new node

if (node == NULL) return newNode(key);

// Otherwise, recur down the tree

if (key < node->key)

node->left = insert(node->left, key);

else if (key > node->key)

node->right = insert(node->right, key);


// return the (unchanged) node pointer

return node;
}
// function to do inorder traversal of BST
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%c ", root->key);
inorder(root->right);
}
}
// function to do preorder traversal of BST
void preorder(struct node *root)
{
if (root != NULL)
{
printf("%c ", root->key);
preorder(root->left);
preorder(root->right);
}
}
// function to do postorder traversal of BST
void postorder(struct node *root)
{
if (root != NULL)
{
postorder(root->left);
postorder(root->right);
printf("%c ", root->key);
}
}


// Main Function

int main()
{
struct node *root = NULL;
int m;
printf("Enter the max value and elements:");
scanf("%d", &m);
for(int i=0;i<m;i++)
{
char ap;
//printf("enter the element:");
scanf("%c", &ap);
int n = ap;
// printf("%d\n",n);
if(i==0)
{
root=insert(root,n);

}
else
{
insert(root,n);

}
}
// print inoder traversal of the BST
printf("\n inorder traversal: \n");
inorder(root);
printf("\n preorder traversal: \n");
// print preoder traversal of the BST
preorder(root);
// print postoder traversal of the BST
printf("\n postorder traversal:\n");
postorder(root);
return 0;
}

0 comments on commit ac90e3a

Please sign in to comment.