This is not a demand of service question and not part of any homework assignment or work related question. I just happen to read some sample Qs in a text book and found this particular question very interesting.
As I mentioned in Re: Least common ancestor function implemented in perl (Homework)
homework, no matter the "teacher" (which could be yourself). Please read what I wrote there about annotation.
But since i'm pretty new to perl, i couldnt do it myself hence posted here.
If you can't even begin to solve the problem in Perl (or any other language) in order to show us what you've done, then you need to start with much smaller problems.