Мне нужно построить дерево, которое, начиная с строки, продолжает создавать новые узлы в соответствии с некоторыми правилами трансформации.Построить дерево N-arry (рекурсивно?) В C
Например:
Получая строку aab
И следующие два правила преобразования:
ab --> bba
b --> ba
Следующая дерево должны быть построены:
Обратите внимание, что сборка выполняется в широтном режиме. На каждом шаге я применяю все правила преобразования для каждой подстроки текущего узла, и это будут дети.
Вот то, что я до сих пор:
//Representing the n_ary tree
typedef struct {
char *value;
struct t_children_list *children;
} tree;
typedef struct t_children_list {
tree *child;
struct t_children_list *next;
} children_list;
void initializeNode(tree **node, char *input)
{
if((*node = malloc(sizeof(tree))) == NULL) { abort(); }
(*node)->value = input;
(*node)->children = NULL;
}
void createChildrenList(children_list **children, tree *transformation)
{
if((*children = malloc(sizeof(children_list))) == NULL) { abort(); }
(*children)->child = transformation;
(*children)->next = NULL;
}
//Given a node, and a needle with a replacement. It will add the childrens to that node.
void addTransformationsToNode(tree **origin, char *needle, char *replacement)
{
char *str = (*origin)->value;
for (char *p = str; *p != '\0'; p++) {
//Logic to find the value of str_... Not relevant
tree *transformation = NULL;
initializeNode(&transformation, str_);
//Add node to origin children list
// If node doesn't have children yet, create a new list
// Otherwise, add to end of children list
children_list *children = NULL;
createChildrenList(&children, transformation);
if ((*origin)->children == NULL) {
(*origin)->children = children;
} else {
children_list *current = (*origin)->children;
while (current->next != NULL) {
current = current->next;
}
current->next = children;
}
}
}
}
void main()
{
// Create the tree
char *input = "aab";
char *target = "bababab";
tree *my_tree = NULL;
initializeNode(&my_tree, input);
addTransformationsToNode(&my_tree, "ab", "bba");
addTransformationsToNode(&my_tree, "b", "ba");
}
Это работает правильно для первого уровня. Но я ищу способ, которым я мог бы сделать то же самое для каждого узла и дочерних узлов этого узла. Итак, я начинаю с начала, нахожу все преобразования, а затем для трансформаций достижений делают то же самое. Я не вижу, как я мог бы сделать это рекурсивно ...
Спасибо!
возможно дубликат [Сделать дерево растет горизонтально применяя изменения к текущему узлу] (http://stackoverflow.com/questions/15048037/make-a-tree-grow-horizontally-applying-modifications-to- current-node) –