binary tree compare: multiple solutions solver

This commit is contained in:
2021-01-26 11:52:06 +01:00
parent 2e83f4b833
commit c1d0085217
3 changed files with 71 additions and 12 deletions

54
tree.c
View File

@@ -54,6 +54,49 @@ void free_node(node)
freenodes=node;
}
int compare_nodes(node1, node2, depth)
NODE *node1, *node2;
int depth;
{
int equal=0;
// we must also consider the case n1->left == n2->right, and vice-et-versa.
# ifdef DEBUG_TREE
if (depth==0) {
printf("compare trees: [ ");
print_node(node1, TREE_TOP, 0, 4);
printf(" ] and [ ");
print_node(node2, TREE_TOP, 0, 4);
printf(" ] ");
}
# endif
if (node1->type==node2->type) {
switch (node1->type) {
case TREE_LEAF:
if (node1->val==node2->val)
equal=1;
break;
case TREE_NODE:
if (node1->op == node2->op) {
if (compare_nodes(node1->left, node2->left, depth+1) &&
compare_nodes(node1->right, node2->right, depth+1)) {
equal=1;
} else if (compare_nodes(node1->left, node2->right, depth+1) &&
compare_nodes(node1->right, node2->left, depth+1)) {
equal=1;
}
}
break;
}
}
# ifdef DEBUG_TREE
if (depth==0) {
printf(" = %d\n", equal);
}
# endif
return equal;
}
void print_node(node, side, depth, details)
NODE *node;
char side;
@@ -120,7 +163,7 @@ void print_node(node, side, depth, details)
printf(")");
}
break;
case 2:
case 2: /* tree */
/* left padding */
for (i=0; i<=depth; ++i)
printf(" ");
@@ -181,6 +224,7 @@ TREE *new_tree(name)
return tree;
}
NODE *dup_node(src)
NODE *src;
{
@@ -269,14 +313,14 @@ void gen_reduced_trees(n)
};
char *seq4[]= {
"101010100",
"110010100",
"101100100"
"101100100",
"110010100"
};
char *seq5[]= {
"10101010100",
"11001010100",
"10110010100",
"10101100100",
"10110010100",
"11001010100",
"11001100100",
"11010010100"
};