Advertisement
JohnathanMayhem

first

Dec 14th, 2021
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.35 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <malloc.h>
  3. #include <string.h>
  4.  
  5. struct binary_tree{
  6.     int root;
  7.     struct binary_tree *left, *right;
  8. };
  9. struct binary_tree* new_binary_tree(int x){
  10.     struct binary_tree *p;
  11.     p =(struct binary_tree*) malloc(sizeof(struct binary_tree));
  12.     p->root= x;
  13.     p->left = NULL;
  14.     p->right = NULL;
  15.     return p;
  16. }
  17. void inorderPref(struct binary_tree *root)
  18. {
  19.     if(root!=NULL)
  20.     {
  21.         printf("%d ", root->root);
  22.         inorderPref(root->left);
  23.         inorderPref(root->right);
  24.     }
  25. }
  26. void inorderPost(struct binary_tree *root)
  27. {
  28.     if(root!=NULL)
  29.     {
  30.         inorderPost(root->left);
  31.         inorderPost(root->right);
  32.         printf("%d ", root->root);
  33.     }
  34. }
  35. struct binary_tree* insert(struct binary_tree *root, int x){
  36.     if(root==NULL)
  37.         return new_binary_tree(x);
  38.     else
  39.         if(x>root->root)
  40.             root->right = insert(root->right, x);
  41.     else
  42.         if (x < root->root)
  43.             root->left = insert(root->left,x);
  44.     return root;
  45. }
  46.  
  47. int main(){
  48.     struct binary_tree *root;
  49.     FILE *file;
  50.     file = fopen("input.txt", "r");
  51.     int n;
  52.     fscanf(file, "%d", &n);
  53.     root = new_binary_tree(n);
  54.     while (fscanf(file, "%d", &n)==1){
  55.         insert(root, n);
  56.     }
  57.     inorderPref(root);
  58.     printf("\n");
  59.     inorderPost(root);
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement