I checked all around the internet to find out how to check if a tree is a subSet of another. By subset, I mean The issubset
function should return 1
if all the elements of the first tree appear in the second tree
and 0
otherwise. Note that depending on the insertion order of elements, two trees with same set of elements can have very different shapes. Given the following examples as trees:
Elements of the first tree
4
/ \
2 6
/ \ / \
1 2 5 7
Elements of the second Tree
6
/ \
4 7
/ \
2 5
/ \
1 2
The following code traverses the trees then checks the values:
int issubset(nodeT **tree1, nodeT **tree2) {
if( *tree2 == NULL)
return TRUE;
if(*tree1 == NULL)
return FALSE;
if(are_identical(&(*tree1),&(*tree2)))
return TRUE;
return issubset(&(*tree1)->pLeft, &(*tree2)) || issubset(&(*tree2)->pRight, &(*tree2));
}
int are_identical(nodeT **tree1, nodeT **tree2) {
nodeT **temp;
int iFound = 0, i, r;
if( *tree2 == NULL)
return TRUE;
if( (*tree1) ==NULL && (*tree2) ==NULL) {
return FALSE;
}
if( (*tree1)->iValue != (*tree2)->iValue) {
if(iFound = 0)
return TRUE;
i = issubset(&(*tree1)->pLeft, &(*tree2));
if( i ==0) {
r = issubset(&(*tree1)->pRight, &(*tree2));
return r;
}
return i;
}
return((*tree1)->iValue == (*tree2)->iValue && are_identical(&(*tree1)->pLeft, &(*tree2)->pLeft) &&
are_identical(&(*tree1)->pRight, &(*tree2)->pRight) );
}
After running my code with the given examples, my output gives back that the first tree is not a subset of the second, when it actually is a subset.