Ideal Paths In A Labelled Tree

Company: Tech Mahindra_9nov

Difficulty: medium

Problem Statement

Ideal Paths In A Labelled Tree A tree with N vertices is handed to you. The vertices carry the labels 1 through N , but the labels were handed out in no particular order, so a vertex's label tells you nothing about where it sits in the tree. The shape of the tree is given by an array A of N numbers, where A[i] describes vertex i : * if A[i] is not 0 , there is an edge between vertex i and vertex A[i] , and A[i] is called the parent of vertex i ; * exactly one entry of A is 0 , and the vertex at that position is the root of the tree. If the same number appears at two positions of A , then that number is the parent of both of those vertices. No number appears at more than two positions, so a vertex has at most two children. Between any two different vertices X and Y there is exactly one path, and it is a path that never repeats a vertex. Take X < Y . The path is called an ideal path when every vertex lying on it carries a label inside the closed range from X to Y . The two ends t