hozer

binary tree (numbers) [working]

May 7th, 2014
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.92 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. void print(node *head)
  24. {
  25.     if (!head) return;
  26.     reprint(head->left);
  27.     printf("%d ", head->data);
  28.     reprint(head->right);
  29. }
  30.  
  31. int height(node *head)
  32. {
  33.     int hl, hr;
  34.     if (!head) return 0;
  35.     hl = height(head->left) + 1;
  36.     hr = height(head->right) + 1;
  37.    
  38.     return hl > hr ? hl : hr;
  39. }
  40.  
  41. int main()
  42. {
  43.     int n;
  44.     node *head = NULL;
  45.     printf("input tree: ");
  46.     while (1)
  47.     {
  48.         scanf("%d", &n);
  49.         if (!n) break;
  50.         head = addNode(head, n);
  51.     }
  52.     print(head);
  53.     printf("\n%d", height(head));
  54.     _getch();
  55.     return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment