• B правой части каждого сообщения есть стрелки и . Не стесняйтесь оценивать ответы. Чтобы автору вопроса закрыть свой тикет, надо выбрать лучший ответ. Просто нажмите значок в правой части сообщения.

  • Курсы Академии Кодебай, стартующие в мае - июне, от команды The Codeby

    1. Цифровая криминалистика и реагирование на инциденты
    2. ОС Linux (DFIR) Старт: 16 мая
    3. Анализ фишинговых атак Старт: 16 мая Устройства для тестирования на проникновение Старт: 16 мая

    Скидки до 10%

    Полный список ближайших курсов ...

Очистка Деревьем (есть Код)

  • Автор темы nikblow
  • Дата начала
N

nikblow

Написал код для создания и отображения дерева (еле еле получилось)


C++:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct tree
{
int data;
struct tree *left;
struct tree *right;
} tree_1;
void tree_go(struct tree *tree_1, int max_level, int current)
{
tree_1=(struct tree*)malloc(sizeof(struct tree));
tree_1->data=1+rand()%20;
printf("\nlevel %d: %d", current, tree_1->data);
if(current==max_level)
{
tree_1->left=0;
tree_1->right=0;
}
else
{
tree_1->left=(struct tree*)malloc(sizeof(struct tree));
tree_go(tree_1->left, max_level, current+1);
tree_1->right=(struct tree*)malloc(sizeof(struct tree));
tree_go(tree_1->right, max_level, current+1);
}
}
void clear(struct tree *tree_1, int max_level, int current)
{

}
int main()
{
srand(time(NULL));
struct tree *data;
int level=0;
printf("\nPlease type max level your tree: ");
scanf("%d", &level);

data=(struct tree*)malloc(sizeof(struct tree));
tree_go(data, level, 1);
// clear tree
printf("\n\nThe end");
return 0;
}

теперь мне нужно очистить память из под каждого элемента. Я так понимаю мне нужно написать функцию, которая будет проходит дерево до конца, обнулять последние элементы и очищать память, далее вызываться рекурсивно, чтобы очистить таким образом всё дерево

Я не могу понять, что написать, чтобы пройти дерево до конца. Та же проблема была с выводом, поэтому впихнул его в функцию создания, работает. С очисткой всё сложнее

если возможно напишите пример кода =/ на словах очень сложно понять


Попробовал создать процедуру очистки. Программа работает, но не знаю очищается ли память, подскажите правильно ли? И если нет, то что переделать

C++:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct tree
{
int data;
struct tree *left;
struct tree *right;
} tree_1;
void tree_go(struct tree *tree_1, int max_level, int current, int summ)
{
tree_1=(struct tree*)malloc(sizeof(struct tree));
tree_1->data=1+rand()%20;
printf("\nlevel %d: %d", current, tree_1->data);
if(current==max_level)
{
tree_1->left=NULL;
tree_1->right=NULL;
}
else
{
tree_1->left=(struct tree*)malloc(sizeof(struct tree));
tree_go(tree_1->left, max_level, current+1, summ);
tree_1->right=(struct tree*)malloc(sizeof(struct tree));
tree_go(tree_1->right, max_level, current+1, summ);
}
}
void clear(struct tree *tree_1, int max_level, int current)
{
if(current==max_level)
{
free(&tree_1->data);
}
else
{
clear(tree_1->left, max_level, current-1);
clear(tree_1->right, max_level, current-1);
}
}
int main()
{
srand(time(NULL));
struct tree *data;
int level=0, summ=0;
printf("\nPlease type max level your tree: "),
scanf("%d", &level);
printf("\nWhat level summ:");
data=(struct tree*)malloc(sizeof(struct tree));
tree_go(data, level, 1, summ);
clear(data, level, level);
printf("\n\nThe end");
free(data);
return 0;
}

Программирую в среде xcode и VS2012
 
W

Whatka

не совсем так
вам нужно идти по дереву обратным левым обходом(от листьев вверх)
+ перед каждым вызовом функции проверка на существование вершины куда хотиде перейти
то есть
C++:
//
void clear(struct tree *tree_1)
{
if(tree_1->left)
clear(tree_1->left);
if(tree_1->right)
clear(tree_1->right);// сначала спускаетесь до листьев,а потом только начинаете освобождать память
//освобождение памяти, оьнуление указателей и т.д.  
}
//
 
Мы в соцсетях:

Обучение наступательной кибербезопасности в игровой форме. Начать игру!