//traversal of a tree--recursive traversal#include <stdio.h>#include<stdlib.h>#include<string.h>typedefstruct_treenode{//data fields Chardata; //pointer Field struct_treenode * LEFTCHILD;//left child pointer struct_treenode * RIGHTCHILD;//Right Child pointer}treenode, *Treenodepointer;//First Order Traversal voidprintroot (treenodepointer root) {if(root!=NULL) { //Accessing the root nodeprintf"%c", root->data); //Access left subtreePrintroot (root->leftchild); //access to the right sub-treePrintroot (root->rightchild); }} //Middle Sequence TraversalvoidPrintRoot2 (treenodepointer root) {if(Root! =NULL) { //Access left subtreePrintRoot2 (root->leftchild); //Accessing the root nodeprintf"%c", root->data); //access to the right sub-treePrintRoot2 (root->rightchild); }}//Post-post traversalvoidPrintRoot3 (treenodepointer root) {if(Root! =NULL) { //Access left subtreePRINTROOT3 (root->leftchild); //access to the right sub-treePRINTROOT3 (root->rightchild); //Accessing the root nodeprintf"%c", root->data); }}voidTest2 () {//defining the structure body objectTreenodepointer t1 = null, t2 = null, T3 = null, T4 = null, T5 =NULL; T1= (Treenodepointer)malloc(sizeof(TreeNode)); if(T1 = =NULL) {printf ("failed to allocate memory! "); GotoEND; } //Initializing Datamemset (T1,0,sizeof(TreeNode)); T2= (Treenodepointer)malloc(sizeof(TreeNode)); if(T2 = =NULL) {printf ("failed to allocate memory! "); GotoEND; } //Initializing Datamemset (T2,0,sizeof(TreeNode)); T3= (Treenodepointer)malloc(sizeof(TreeNode)); if(T3 = =NULL) {printf ("failed to allocate memory! "); GotoEND; } //Initializing Datamemset (T3,0,sizeof(TreeNode)); T4= (Treenodepointer)malloc(sizeof(TreeNode)); if(T4 = =NULL) {printf ("failed to allocate memory! "); GotoEND; } //Initializing Datamemset (T4,0,sizeof(TreeNode)); T5= (Treenodepointer)malloc(sizeof(TreeNode)); if(T5 = =NULL) {printf ("failed to allocate memory! "); GotoEND; } //Initializing Datamemset (T5,0,sizeof(TreeNode)); //Populating data fieldsT1->data ='A'; T2->data ='B'; T3->data ='C'; T4->data ='D'; T5->data ='E'; //establish a relationship between treesT1->leftchild =T2; T1->rightchild =T3; T2->leftchild =T4; T2->rightchild =NULL; T3->leftchild =T5; T3->rightchild =NULL; //T5 is T4 's left child.T4->leftchild =NULL; T4->rightchild =NULL; //T5 No child nodesT5->leftchild =NULL; T5->rightchild =NULL; //Recursive traversal treeprintf"First Order traversal \ n"); Printroot (t1); printf ("\ n"); printf ("middle order traversal \ n"); PrintRoot2 (t1); printf ("\ n"); printf ("Post- traversal \ n"); PRINTROOT3 (t1); END:if(T1! =NULL) { Free(t1); T1=NULL; } if(T2! =NULL) { Free(T2); T2=NULL; } if(T3! =NULL) { Free(T3); T3=NULL; } if(T4! =NULL) { Free(T4); T4=NULL; } if(T5! =NULL) { Free(T5); T5=NULL; }}voidMain () {Test2 (); printf ("\ n"); System ("Pause");}
Traversal of the data structure tree (recursive traversal)