Algorithms of tree

verified by all the test cases [online judge]:)