I think the problem is that a children could have more than 1 parent - and here you have to check if all of his parents have been printed. If you can't find the solution yourself - write and I will tell you a way.
P.S. Other people say that "One of the lines in test 4 has trailing space. This old problem was designed for Pascal/C++, such inputs treated as a bad style nowadays." I don't know what this means, but first check if this is the problem!