text: Tree Traversals ( Inorder , Preorder and Postorder ) | C program for different tree traversals ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Given a binary tree , print its nodes according to the " bottom - up " postorder traversal . ; first recur on left subtree ; then recur on right subtree ; now deal with the node ; Given a binary tree , print its nodes in inorder ; first recur on left child ; then print the data of node ; now recur on right child ; Given a binary tree , print its nodes in preorder ; first print data of node ; then recur on left sutree ; now recur on right subtree ; Driver program to test above functions
code: #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE 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 printPostorder ( struct node * node ) { if ( node == NULL ) return ; printPostorder ( node -> left ) ; printPostorder ( 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 printPreorder ( struct node * node ) { if ( node == NULL ) return ; printf ( " % d ▁ " , node -> data ) ; printPreorder ( node -> left ) ; printPreorder ( 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 ( " Preorder traversal of binary tree is " printPreorder ( root ) ; printf ( " Inorder traversal of binary tree is " printInorder ( root ) ; printf ( " Postorder traversal of binary tree is " printPostorder ( root ) ; getchar ( ) ; return 0 ; }