我正在尝试从两个列表中创建所有可能的值对组合的树结构
我有两个链接列表L1 = {A, B, C}
和L2 = {1, 2, 3}
。我想创建一个树结构,让我可以提取这两个列表的所有独特组合:
root--A1--B2--C3
| | |
| | --B3--C2
| |
| A2--B1--C3
| |
| --B3--C1
|
--A3--B1--C2
|
--B2--C1
每个列表中任何成员的只有1个实例可以位于树的任何完整分支中。我希望这适用于任何大小的L1,L2
树的要求:
每个分支必须尽可能长
我的树由2个结构组成:
typedef struct _TR tree;
typedef struct _TN tree_node;
struct _TR
{
unsigned int tree_depth;
tree_node * root;
};
struct _TN
{
List_item * items[2];
unsigned int node_count;
tree_node * parent_node;
tree_node ** child_nodes;
};
树由以下函数构建
void addToAllBranches(List_item * item_array[2], tree_node * curr_node)
{
if (curr_node->node_count == 0) // Problem, some how
{
if (!checkIfExistsInBranch(curr_node->parent_node, item_array)) // Checks if any member of the pair exists in the current branch (straight following each parent node)
addNode(curr_node, createNode(item_array)); //If it doesn't exist, add it. Otherwise do nothing
return;
}
int i = 0;
while (i < curr_node->node_count)
{
addToAllBranches(item_array, curr_node->child_nodes[i]);
i++;
}
}
由
调用/* Walks through each possible pair and tries to add them to the tree*/
void addPairsToTree(List * L1, List * L2, tree * root_tree)
{
List_item * L1_list_wlkr = L1->top_item;
List_item * L2_list_wlkr;
List_item * item_array[2];
while (L1_list_wlkr != NULL)
{
L2_list_wlkr = L2->top_item;
while (L2_list_wlkr != NULL)
{
item_array[0] = L1_list_wlkr;
item_array[1] = L2_list_wlkr;
addToAllBranches(item_array, root_tree->root);
L2_list_wlkr = L2_list_wlkr->next_item;
}
L1_list_wlkr = L1_list_wlkr->next_item;
}
}
使用检查功能:
int checkIfExistsInBranch(tree_node * curr_node, List_item * check[2])
{
tree_node * tree_wlkr = curr_node;
while(tree_wlkr != NULL)
{
if(tree_wlkr->items[0] == check[0] || tree_wlkr->items[1] == check[1])
{
return 1;
}
tree_wlkr = tree_wlkr->parent_node;
}
return 0;
}
看看树形结构,我觉得它看起来像这样:
root--A1--A2--B2--B3--C3
哪个没有意义,我觉得输出应该是:
root--A1--B2--C3
我很确定问题是由行引起的:
if (curr_node->node_count == 0) // Problem, some how
这导致添加功能仅添加到空分支上 我不确定如何改变它仍然使树满足尺寸要求。
我的问题是:
if (curr_node->node_count == 0) // Problem, some how
行更改为?checkIfExistsInBranch
如何以当前实施算法的方式失败?