text: Print Binary Tree in 2 | Program to print binary tree in 2D ; A binary tree node ; Helper function to allocates a new node ; Function to print binary tree in 2D It does reverse inorder traversal ; Base case ; Increase distance between levels ; Process right child first ; Print current node after space count ; Process left child ; Wrapper over print2DUtil ( ) ; Pass initial space count as 0 ; Driver program to test above functions
code: #include <stdio.h> NEW_LINE #include <malloc.h> NEW_LINE #define COUNT  10 NEW_LINE struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int data ) { struct Node * node = malloc ( sizeof ( struct Node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return node ; } void print2DUtil ( struct Node * root , int space ) { if ( root == NULL ) return ; space += COUNT ; print2DUtil ( root -> right , space ) ; printf ( " STRNEWLINE " ) ; for ( int i = COUNT ; i < space ; i ++ ) printf ( " ▁ " ) ; printf ( " % d STRNEWLINE " , root -> data ) ; print2DUtil ( root -> left , space ) ; } void print2D ( struct Node * root ) { print2DUtil ( root , 0 ) ; } 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 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> left -> left -> left = newNode ( 8 ) ; root -> left -> left -> right = newNode ( 9 ) ; root -> left -> right -> left = newNode ( 10 ) ; root -> left -> right -> right = newNode ( 11 ) ; root -> right -> left -> left = newNode ( 12 ) ; root -> right -> left -> right = newNode ( 13 ) ; root -> right -> right -> left = newNode ( 14 ) ; root -> right -> right -> right = newNode ( 15 ) ; print2D ( root ) ; return 0 ; }