Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Скачиваний:
27
Добавлен:
19.04.2015
Размер:
2.06 Кб
Скачать
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

typedef struct tag_tree {
  int info;
  struct tag_tree *left, *right;
} TREE;

TREE* add_node(TREE* root, int info){
  TREE* node;
  TREE* new_node = (TREE *) malloc(sizeof(TREE));
  new_node->info = info;
  new_node->left  = NULL;
  new_node->right = NULL;
  while (root){
    node = root;
    //root = (root->info > info) ? root->left : root->right;
    //DEBUG
     if (root->info > info){
       printf("root (%d) > info(%d) go left!\n", root->info,info);
       root = root->left;
     } else {
       printf("root (%d) =< info(%d) go rigth!\n", root->info,info);
       root = root->right;
     }
     //END DEBUG
  }
  if (node){
    if (node->info > info){
      node->left = new_node;
    } else {
      node->right = new_node;
    }
  }
  return new_node;
}

TREE* find(TREE* root, int info){
  TREE* node;
  while (root){
    if (root->info == info){
      return root;
    }
    else if (root->info > info){
      root = root->left;
    } else {
      root = root->right;
    }
  }
  return NULL;
}

void show_tree(TREE* node){
  if(node != NULL){
    show_tree(node->left);
    printf("%d ",node->info);
    show_tree(node->right);
  }
}

void del_tree(TREE* node){
  if(node != NULL){
    del_tree(node->left);
    del_tree(node->right);
    printf("\n node %d - deleted",node->info);
    free(node);
  }
}

int main(){
  TREE* root = NULL, *current = NULL;
  int value=0;
  clrscr();
  while(1){
    printf("vvedite chislo (0 dlya vihoda)");
    scanf("%d",&value);
    if (value == 0) {
      break;
    }
    current = add_node(root,value);
    if (!root){
      root = current;
    }
  }
  show_tree(root);
  if (current = find(root,3)){
    printf("For node = %d\n",3);
    if (current->left){
      printf("Left child is %d\n",current->left->info);
    }
    if (current->right){
      printf("Right child is %d\n",current->right->info);
    }
  }
  del_tree(root);
return 0;
}
Соседние файлы в папке 3 mod