Alright guys, I was asked this question in an interview today and it goes like this:
"Tell if one binary tree is contained inside another binary tree or not (contains implies both in structure and value of nodes)"
I thought of the following approach:
Flatten the larger tree as:
{{{-}a{-}}b{{-}c{-}}}d{{{-}e{{-}f{-}}}g{{{-}h{-}}i{{-}j{-}}}}
(I did actually write code for this, {-}
implies empty left or right sub-tree, each sub-tree is enclosed within {} paranthesis)
Now for smaller sub-tree we need to match this pattern:
{{.*}e{.*}}g{{{.*}h{.*}}i{{.*}j{.*}}}
where {.*}
denotes an empty or non-empty sub-tree.
At the time I thought, this will be a trivial regex pattern matching problem in java but I am bamboozled. Actually now I feel, I have just transformed the problem (created one monster out of another).
Is there a simple regex one liner to match these patterns? I understand there might be other approaches to solve this problem and this might not be the best one. I just wonder if this is solvable.