![]() |
VOOZH | about |
Given a tree with N vertices numbered from 0 to N – 1 and Q queries containing nodes in the tree, the task is to find the distance of given node from root node for multiple queries. Consider 0th node as the root node and take the distance of the root node from itself as 0.
Examples:
Tree: 0 / \ 1 2 | / \ 3 4 5 Input: 2 Output: 1 Explanation: Distance of node 2 from root is 1 Input: 3 Output: 2 Explanation: Distance of node 3 from root is 2
Approach:
Start by assigning the distance of the root node as 0. Then, traverse the tree using Breadth First Traversal(BFS). When marking the children of the node N as visited, also assign the distance of these children as the distance[N] + 1. Finally, for different queries, the value of the distance array of the node is printed.
Below is the implementation of above approach:
1 2
Time Complexity: O(n+m) where n is the number of vertices and m is the number of edges in the tree.
Space Complexity: O(n)