Inorder Preorder Postorder in C

C algorithm for tree traversal using the In order, Preorder, Post order method. These methods in tree traversal using the preorder, post order, and in order used to execute the tree traversal in the C programming language.

What is Tree traversal?

Tree traversal is a type of graph traversal in computer science that refers to the process of visiting each node in a tree data structure exactly once. The sequence in which the nodes are visited is used to classify these traversals. 

What is In order traversal?

Traversal in reverse sequence. In an in order traversal, the left child is visited first, followed by the node, and finally the right child. This traversal is used by the binary search tree to print all nodes in ascending order of value.

What is Preorder traversal?

Process all nodes of a tree by starting with the root and working your way down to all subtrees. Prefix traversal is another name for it.

What is post-order traversal?

The term “tree traversal” refers to visiting all of a tree’s nodes exactly once. Visiting a node entails doing something with it. It may be something as simple as printing the node. One of the many methods for traversing a tree is post-order traversal.

#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
void printpost(struct node* node)
{
if (node == NULL)
return;
printpost(node->left);
printpost(node->right);
printf("%d ", node->data);
}
void printinorder(struct node* node)
{
if (node == NULL)
return;
printinorder(node->left);
printf("%d ", node->data);
printinorder(node->right);
}
void printpre(struct node* node)
{
if (node == NULL)
return;
printf("%d ", node->data);
printpre(node->left);
printpre(node->right);
}
int main()
{
struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("\npre traversal of binary tree is \n");
printpre(root);
printf("\ninorder traversal of binary tree is \n");
printinorder(root);
printf("\npost traversal of binary tree is \n");
printpost(root);
getchar();
return 0;
}

 

Output:

pre traversal of binary tree is
1 2 4 5 3
inorder traversal of binary tree is
4 2 5 1 3
post traversal of binary tree is
4 5 2 3 1