Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifdef _MSC_VER
- // Annex K нинужен. Блядские ворнинги - тем более.
- #define _CRT_SECURE_NO_WARNINGS
- #endif
- #include <string.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdint.h>
- //дерево
- typedef struct bTREE
- {
- int inf;
- struct bTREE* left;
- struct bTREE* right;
- }TREE;
- //очередь
- typedef struct qQUEUE
- {
- TREE *tr;
- struct qQUEUE *next;
- }QUEUE;
- QUEUE *q;
- //функция добавления элемента в очередь
- void Put(TREE *a)
- {
- QUEUE *n, *prev;
- prev = q;
- n = malloc(sizeof(QUEUE));
- n->tr = a;
- n->next = NULL;
- if (q != NULL)
- {
- while (prev->next != NULL)
- prev = prev->next;
- prev->next = n;
- }
- else
- q = n;
- }
- //функция удаления элемента из очереди
- TREE* Get(void)
- {
- QUEUE *prev;
- TREE *a;
- if (q != NULL)
- {
- prev = q;
- a = q->tr;
- if (q->next != NULL)
- q = q->next;
- else
- q = NULL;
- free(prev);
- return a;
- }
- else
- return NULL;
- }
- //функция проверки на пустоту очереди
- int Empty(QUEUE *q)
- {
- if (q == NULL) return 1;
- else return 0;
- }
- //функция добавления элемента в дерево
- TREE* Add(TREE *root, int x)
- {
- if (root == NULL)
- {
- root = malloc(sizeof(TREE));
- root->inf = x;
- root->left = root->right = NULL;
- }
- else {
- if (x <= root->inf)
- root->left = Add(root->left, x);
- else
- root->right = Add(root->right, x);
- }
- return root;
- }
- //функция вывода дерева на экран обходя дерево в ширину
- int ShowTree(TREE *tree, size_t target_depth)
- {
- TREE *node;
- size_t depth = 0;
- Put(tree);
- Put(NULL);
- while (1)
- {
- if (depth == target_depth) {
- // Находимся на нужном уровне? Выводим содержимое очереди. В конце
- // будет NULL, проверка на Empty избыточна.
- size_t count = 0;
- printf("\nList of elements at depth == %zu: ", target_depth);
- while ((node = Get()) != NULL) {
- printf("%d ", node->inf);
- count++;
- }
- printf("\n");
- return count;
- }
- node = Get();
- if (node == NULL) {
- printf("(at depth %zu)\n", depth);
- // У нас закончились элементы для текущей глубины, но ни у одного
- // из них не было потомков? Значит, мы уже не сможем опуститься до
- // запрашиваемой глубины, поэтому выходим нахуй, чтобы не попасть
- // в бесконечный цикл.
- if (Empty(q)) {
- return 0;
- }
- Put(NULL);
- depth++;
- } else {
- if (node->left != NULL)
- Put(node->left);
- if (node->right != NULL)
- Put(node->right);
- printf("%d ", node->inf);
- }
- }
- }
- int main(void)
- {
- TREE *tree = NULL;
- static int tree_data[] = { 13, 10, 5, 12, 20, 15, };
- for (size_t i = 0; i < sizeof(tree_data) / sizeof(tree_data[0]); i++) {
- tree = Add(tree, tree_data[i]);
- }
- printf("Number of elements at given depth = %zu\n", ShowTree(tree, 2));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement