voltage

bst

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