text: Reverse Level Order Traversal | A recursive C program to print REVERSE level order traversal ; A binary tree node has data , pointer to left and right child ; Function protoypes ; Function to print REVERSE level order traversal a tree ; Print nodes at a given level ; Compute the " height " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node . ; compute the height of each subtree ; use the larger one ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver program to test above functions ; Let us create trees shown in above diagram
code: #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; void printGivenLevel ( struct node * root , int level ) ; int height ( struct node * node ) ; struct node * newNode ( int data ) ; void reverseLevelOrder ( struct node * root ) { int h = height ( root ) ; int i ; for ( i = h ; i >= 1 ; i -- ) printGivenLevel ( root , i ) ; } void printGivenLevel ( struct node * root , int level ) { if ( root == NULL ) return ; if ( level == 1 ) printf ( " % d ▁ " , root -> data ) ; else if ( level > 1 ) { printGivenLevel ( root -> left , level - 1 ) ; printGivenLevel ( root -> right , level - 1 ) ; } } int height ( struct node * node ) { if ( node == NULL ) return 0 ; else { int lheight = height ( node -> left ) ; int rheight = height ( node -> right ) ; if ( lheight > rheight ) return ( lheight + 1 ) ; else return ( rheight + 1 ) ; } } 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 ) ; } 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 ( " Level ▁ Order ▁ traversal ▁ of ▁ binary ▁ tree ▁ is ▁ STRNEWLINE " ) ; reverseLevelOrder ( root ) ; return 0 ; }