Advertisement
afrinahoque

Insert and Preorder

Dec 10th, 2019
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.15 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. typedef struct node
  4. {
  5.     int a;
  6.     struct node *left, *right;
  7. }node;
  8.  
  9. node *root=NULL, *temp=NULL;
  10.  
  11. void insert(node *N, node *temp)
  12. {
  13.  
  14.         if(N->a<temp->a)
  15.         {
  16.             if(temp->left==NULL)
  17.             {
  18.                 temp->left=N;
  19.             }
  20.             else
  21.             {
  22.                 insert(temp->left, N);
  23.             }
  24.         }
  25.             else
  26.             {
  27.                 if(temp->right==NULL)
  28.                 {
  29.                     temp->right=N;
  30.                 }
  31.                 else
  32.                 {
  33.                     insert(temp->right, N);
  34.                 }
  35.             }
  36.         }
  37.  
  38. void preorder()
  39. {
  40.     while(temp!=NULL)
  41.     {
  42.         printf("Preorder: %d ", temp->a);
  43.         preorder(temp->left);
  44.         preorder(temp->right);
  45.     }
  46. }
  47.  
  48. int main()
  49. {
  50.     int i;
  51.     for(i=0; i<9; i++)
  52.     {
  53.         node *N=(node*)malloc(sizeof(node));
  54.     scanf("%d", &N->a);
  55.     N->left=NULL;
  56.     N->right=NULL;
  57.  
  58.     if(root==NULL)
  59.     {
  60.         root=N;
  61.         return;
  62.     }
  63.     else
  64.     {
  65.         insert(root, N);
  66.     }
  67.     }
  68.     preorder();
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement