Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct _node {
- int data;
- struct _node *right, *left;
- } node;
- node *addNode(node *head, int num)
- {
- node *el = (node*) malloc(sizeof(node));
- el->left = NULL;
- el->right = NULL;
- el->data = num;
- if (!head)
- return el;
- if (head->data > num) head->left = addNode(head->left, num);
- else head->right = addNode(head->right, num);
- return head;
- }
- //print tree in line
- void reprint(node *head)
- {
- if (!head) return;
- reprint(head->left);
- printf("%d ", head->data);
- reprint(head->right);
- }
- //get height of tree
- int height(node *head)
- {
- int hl, hr;
- if (!head) return 0;
- hl = height(head->left) + 1;
- hr = height(head->right) + 1;
- return hl > hr ? hl : hr;
- }
- //structured print of tree
- void print(node *head, int level, int curr)
- {
- if (!head) return;
- print(head->left, level, curr+1);
- if (level == curr) printf("%d\t", head->data);
- else putchar('\t');
- print(head->right, level, curr+1);
- }
- void printn(node *head)
- {
- int h, i = 0;
- if(!head) return;
- h = height(head);
- while(i <= h)
- {
- print(head, i++, 0);
- printf("\n");
- }
- }
- //end - structured print of tree
- int main()
- {
- int n;
- node *head = NULL;
- printf("input tree: ");
- while (1)
- {
- scanf("%d", &n);
- if (!n) break;
- head = addNode(head, n);
- }
- printn(head);
- printf("\n%d\n", height(head));
- _getch();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment