Binary Tree Traversals inorder,preorder and postorder.
#include<stdio.h>
struct binaryTree {
int key;
struct binaryTree *right, *left;
};
typedef struct binaryTree node;
void insert(node **tree, int val);
void preorderTraversal(node *root);
void inorderTraversal(node *root);
void postorderTraversal(node *root);
int main() {
node *root;
int i,val,search;
root = NULL;
while(1) {
printf("\n Enter the value (-1 to exit):");
scanf("%d",&val);
if( val == -1)
break;
insert(&root, val);
}
printf("\n Pre-order Traversal:");
preorderTraversal(root);
printf("\n");
printf("\n Inorder Traversal:");
inorderTraversal(root);
printf("\n");
printf("\n Postorder Traversal:");
postorderTraversal(root);
printf("\n");
return 0;
}
void postorderTraversal(node *root) {
if (root != NULL) {
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ",root->key);
}
}
void inorderTraversal(node *root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ",root->key);
inorderTraversal(root->right);
}
}
void preorderTraversal(node *root) {
if (root != NULL)
printf("%d ",root->key);
if (root->left != NULL)
preorderTraversal(root->left);
if (root->right != NULL)
preorderTraversal(root->right);
}
void insert(node **tree, int val) {
if((*tree) == NULL) {
*tree = (node *)malloc(sizeof(node));
(*tree)->key = val;
(*tree)->right=(*tree)->left=NULL;
return;
}
if(val < (*tree)->key)
insert(&(*tree)->left, val);
else if(val > (*tree)->key)
insert(&(*tree)->right, val);
}
No comments:
Post a Comment