문자열에서 시작하여 일부 변환 규칙에 따라 새 노드를 작성하는 트리를 빌드해야합니다. 예를 들어N-ary 트리를 작성하십시오 (재귀 적으로?) 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- 현재 노드) –