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 ; 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
#include <iostream> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; Node ( int data ) { this -> data = data ; left = right = NULL ; } } ; void printPostorder ( struct Node * node ) { if ( node == NULL ) return ; printPostorder ( node -> left ) ; printPostorder ( node -> right ) ; cout << node -> data << " ▁ " ; } void printInorder ( struct Node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; cout << node -> data << " ▁ " ; printInorder ( node -> right ) ; } void printPreorder ( struct Node * node ) { if ( node == NULL ) return ; cout << node -> data << " ▁ " ; printPreorder ( node -> left ) ; printPreorder ( node -> right ) ; } int main ( ) { struct Node * root = new Node ( 1 ) ; root -> left = new Node ( 2 ) ; root -> right = new Node ( 3 ) ; root -> left -> left = new Node ( 4 ) ; root -> left -> right = new Node ( 5 ) ; cout << " Preorder traversal of binary tree is " ; printPreorder ( root ) ; cout << " Inorder traversal of binary tree is " ; printInorder ( root ) ; cout << " Postorder traversal of binary tree is " ; printPostorder ( root ) ; return 0 ; }