我必须构建一棵树,从一个字符串开始,它会根据一些转换规则不断创建新节点。
例如:
给定一个字符串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");
}
这适用于第一级。但我正在寻找一种方法,可以对每个节点和该节点的子节点执行相同的操作。所以,我从原点开始,找到所有的转换,然后为到达转换做同样的事情。我看不到如何递归地做到这一点......
谢谢!