Advertisement
ramytamer

tree test

May 22nd, 2014
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.71 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct Data {
  5.     int id;
  6.     char name[];
  7. }Data;
  8.  
  9. typedef struct Node{
  10.     Data data;
  11.     struct Node *left, *right;
  12. }Node;
  13.  
  14. typedef Node Tree;
  15.  
  16. Node * newNode(int val){
  17.     Node* node = malloc(sizeof(Node));
  18.     node->data.id = val;
  19.     node->left = node->right = NULL;
  20.     return node;
  21. }
  22.  
  23. Node * addRight(Node *root,int val){
  24.     if(root) {
  25.         Node* new = newNode(val);
  26.         root->right = new;
  27.         return new;
  28.     }
  29.     return NULL;
  30. }
  31.  
  32. Node * addLeft(Node *root,int val){
  33.     if(root) {
  34.         Node* new = newNode(val);
  35.         root->left = new;
  36.         return new;
  37.     }
  38.     return NULL;
  39. }
  40.  
  41. void kill(Node * node){ free(node); }
  42.  
  43. // START OF TRAVERSING FUNCTIONS.
  44. void preTravers(Tree *root){
  45.     if(root) {
  46.         printf("[%d]\n", root->data.id);
  47.         preTravers(root->left);
  48.         preTravers(root->right);
  49.     }
  50. }
  51.  
  52. void postTravers(Tree *root){
  53.     if(root) {
  54.         postTravers(root->left);
  55.         postTravers(root->right);
  56.         printf("[%d]\n", root->data.id);
  57.     }
  58. }
  59.  
  60. void inTravers(Tree *root){
  61.     if(root) {
  62.         inTravers(root->left);
  63.         printf("[%d]\n", root->data.id);
  64.         inTravers(root->right);
  65.     }
  66. }
  67. // END OF TRAVERSING FUNCTIONS.
  68.  
  69. // START SHOWING FUNCTIONS.
  70. void inShow(Tree *root,int currentDepth){
  71.     if(root) {
  72.         inShow(root->right,currentDepth+1);
  73.         int i; for(i=0;i<currentDepth;i++) printf("\t");
  74.         printf("%d ", root->data.id);
  75.         inShow(root->left,currentDepth+1);
  76.     }else
  77.         printf("\n");
  78. }
  79. // END SHOWING FUNCTIONS.
  80.  
  81. int main(){
  82.     system("clear");
  83.     Tree *root  = newNode(8);
  84.     Tree *node1 = addLeft(root,2);
  85.     Tree *node2 = addRight(root,10);
  86.     addLeft(node1,1);
  87.     addRight(addRight(node1,4),5);
  88.     addLeft(node2,9);
  89.     addRight(addLeft(addRight(node2,100),50),60);
  90.  
  91.     // preTravers(root);
  92.     // postTravers(root);
  93.     inTravers(root);
  94.  
  95.     // inShow(root,0);
  96.  
  97.     kill(node2);
  98.     kill(node1);
  99.     return 0;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement