hozer

binary tree (numbers+) [working]

May 21st, 2014
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.39 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct _node {
  5.     int data;
  6.     struct _node *right, *left;
  7. } node;
  8.  
  9.  
  10. node *addNode(node *head, int num)
  11. {
  12.     node *el = (node*) malloc(sizeof(node));
  13.     el->left = NULL;
  14.     el->right = NULL;
  15.     el->data = num;
  16.     if (!head)
  17.         return el;
  18.     if (head->data > num) head->left = addNode(head->left, num);
  19.     else head->right = addNode(head->right, num);
  20.     return head;
  21. }
  22.  
  23. //print tree in line
  24. void reprint(node *head)
  25. {
  26.     if (!head) return;
  27.     reprint(head->left);
  28.     printf("%d ", head->data);
  29.     reprint(head->right);
  30. }
  31.  
  32. //get height of tree
  33. int height(node *head)
  34. {
  35.     int hl, hr;
  36.     if (!head) return 0;
  37.     hl = height(head->left) + 1;
  38.     hr = height(head->right) + 1;
  39.    
  40.     return hl > hr ? hl : hr;
  41. }
  42.  
  43. //structured print of tree
  44. void print(node *head, int level, int curr)
  45. {
  46.     if (!head) return;
  47.     print(head->left, level, curr+1);
  48.     if (level == curr) printf("%d\t", head->data);
  49.     else putchar('\t');
  50.     print(head->right, level, curr+1);
  51. }
  52.  
  53. void printn(node *head)
  54. {
  55.     int h, i = 0;
  56.     if(!head) return;
  57.     h = height(head);
  58.  
  59.     while(i <= h)
  60.     {
  61.         print(head, i++, 0);
  62.         printf("\n");
  63.     }
  64. }
  65. //end - structured print of tree
  66.  
  67. int main()
  68. {
  69.     int n;
  70.     node *head = NULL;
  71.     printf("input tree: ");
  72.     while (1)
  73.     {
  74.         scanf("%d", &n);
  75.         if (!n) break;
  76.         head = addNode(head, n);
  77.     }
  78.     printn(head);
  79.     printf("\n%d\n", height(head));
  80.     _getch();
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment