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:
- Find the path from root to the given nodes of a tree for multiple 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
- Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree
- Print nodes at k distance from root
- Count of nodes which are at a distance X from root and leaves
- Print nodes at k distance from root | Iterative
- Iterative program to find distance of a node from root
- Print path from root to all nodes in a Complete Binary Tree
- Queries to check if the path between two nodes in a tree is a palindrome
- Find the winner of the match | Multiple Queries
- Shortest distance between two nodes in an infinite binary tree
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.