So, I have the obvious brute-force algorithm, which goes as follows
int isSubtree (binTree *S, binTree *T)
{
if (S == NULL)
return 0;
return (isEqual (S,T) || isSubtree (S->left, T) || isSubtree (S->right, T));
}
int isEqual (binTree *S, bintree *T)
{
if (S==NULL && T==NULL)
return 1;
if (S==NULL || T==NULL)
return 0;
if (S->val == T->val)
return isEqual(S->left,T->left) && isEqual (S->right,T->right);
else
return 0;
}
But this is O(n²) approach.
I have another approach which goes as follows and is O(n) We, traverse the first tree in inorder fashion and store it in an array. Then we traverse the second tree and store it in inorder fashion. Now if the second array is a subarray of the first, we go ahead and repeat the same procudure for preorder traversal too. If both the queries result TRUE, The tree is subtree of the first tree. Otherwise, not.
Can somebody tell me whether the following algorithm would work or not?
And is there a more space optimized solution to this problem?
Note: I need two arrays, since I am storing the traversals for both the arrays, is there anyway I could just do with one array? Like I would store the inorder traversal of one of the trees, and then use that array to check for the subarray condition while traversing the other tree. Or maybe no extra space but O(n) time complexity?
Note: By sub-array, I mean that the elements should occur consecutively, i.e
{2,3,5} is a subarray of {1,2,3,5} but not a subarray of {1,2,3,4,5}