Page 204 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 204

Unit 12: Introduction to Trees




          Following program show how a binary tree can be represented using arrays:             Notes
          #include<stdio.h>
          #include<conio.h>
          #include<alloc.h>
          struct node
          {
          struct node *left;
          char data;
          struct node *right;
          };
          struct node *buildtree(int);
          void inorder(struct node);
          char arr[]={‘a’,‘b’,‘c’,‘d’,‘e’,‘f’,‘g’,\0’,‘\0’,‘\h’};
          int ic[]={1,3,5,-1,9,-1,-1,-1-,-1,-1};
          int rc[]={2,4,6,-1,-1,-1-,-1,-1,-1,-1};
          void main()
          {
          struct node *root;
          clrscr();
          root=buildtree(0);
          printf(“in-order traversal:\n”);
          inorder(root);
          getch();
          }
          struct node *buildtree(it index)
          {
          struct node *temp=null;
          if(index!=-1)
          {
          temp=(struc node *)malloc (sizeof(struct node));
          temp->left=buildtree(lc[index]);
          temp->data=arr[index];
          temp->right=buildtree(rc[index]);
          }
          return temp;
          }
          void inorder(struct node *root)
          {
          if (root!=null)
          {
          inorder(root->left);
          printf(“%c]t”,root->data);
          inorder(root->right);
          }
          }





                                           LOVELY PROFESSIONAL UNIVERSITY                                   197
   199   200   201   202   203   204   205   206   207   208   209