I need to check two binary trees to see if they are similar… meaning if they have the exact same structure and then the data on the same levels (but the data doesn’t need to be in the same structure)…
Example
A A
| | | |
B C C B
| | | | | | | |
D E F G G D E F
The left binary tree is similar to the right (obviously there are MANY variations!)
Here’s the psuedocode I have thus far:
if( tree1 == NULL && tree2 == NULL ) return TRUE;
if( tree1 == NULL || tree2 == NULL ) return FALSE;
if( tree1->label != tree2->label ) return FALSE;
return ( TRUE
&& ( ( similarTrees(tree1->left, tree2->left)
&& similarTrees(tree1->right, tree2->right))
|| ( similarTrees(tree1->left, tree2->right)
&& similarTrees(tree1->right, tree2->left)) ));
My reasoning was that since the two left sub trees could be equal and the two right sub tree could be equal OR the left and right of one and the right and left of the other could be equal, then this logical recursion should work… it does not, however.
similarTree is the recursive function
Thanks for all your help!
The code and the example does not match.
Code assumes that trees are equal if each subtree contains the same root label and the same children, albeit in an arbitrary order.
The example, on the other hand, does not hold true for this. For example in the left tree, the children of
CareFandG, whereas in the rightGandD.To write code to check if these are similar, you must first clearly define what it means to be similar. E.g. should a label exists in both trees. Should it exists at the same level? Can it occur more than once?