I am trying to write a method that would compare two given trees (haystack and the needle) and record each position of the node from where the pattern of the hay matches as that of the needle's.
Visualization -
Haystack
Needle
If I have a hay as that in the image and the needle as specified, my program should store the position of the nodes starting from which the pattern would match.
For the example stated above, it would be
ROOT, ROOT->L, ROOT->L->L, ROOT->L->R, ROOT->R
I want to see if the pattern matches and the actual value of the node doesn't matter.
This is my implementation so far -
public static boolean isSubtree(Node haystack, Node needle) {
if (needle == null) // Empty Subtree is accepted
return true;
if (haystack == null)
return false;
// If roots are equal, check subtrees
if (haystack != null && needle != null) {
return isSubtree(haystack.getLeftChild(), needle.getLeftChild())
&& isSubtree(haystack.getRightChild(),
needle.getRightChild());
} else {// No match found for this root. Check subtrees
return isSubtree(haystack.getLeftChild(), needle)
|| isSubtree(haystack.getRightChild(), needle);
}
}
Problem - It seems to me that my implementation might be wrong since it is failing in many cases. For instance, it returns true even when the pattern doesn't seem to match starting from that particular Node.
Failure Case -
Using the same needle as specified above, it seems like my program is recording
ROOT, ROOT->L, ROOT->R
I was wondering if someone could please help me figure out if I am doing anything wrong in my comparison method?
Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire