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.
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
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:
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Find the path from root to the given nodes of a tree for multiple queries
- Find distance between two nodes in the given Binary tree for Q queries
- Queries to find distance between two nodes of a Binary tree
- Queries to find distance between two nodes of a Binary tree - O(logn) method
- Find distance from root to given node in a binary tree
- Find parent of each node in a tree for multiple queries
- Find distance between two nodes of a Binary Tree
- Print nodes at k distance from root
- Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree
- Count of nodes which are at a distance X from root and leaves
- Print nodes at k distance from root | Iterative
- Print path from root to all nodes in a Complete Binary Tree
- Iterative program to find distance of a node from root
- Shortest distance between two nodes in an infinite binary tree
- Distance between two nodes of binary tree with node values from 1 to N
- Queries to check if the path between two nodes in a tree is a palindrome
- Minimum distance to visit all the nodes of an undirected weighted tree
- Find the winner of the match | Multiple Queries
- Find K-th smallest element in an array for multiple queries
- Binary Array Range Queries to find the minimum distance between two Zeros
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.