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:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- 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 between two nodes in the given Binary tree for Q queries
- Find node U containing all nodes from a set V at atmost distance 1 from the path from root to U
- 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
- Find distance from root to given node in a binary tree
- Queries to find sum of distance of a given node to every leaf node in a Weighted Tree
- Find parent of each node in a tree for multiple queries
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Count nodes within K-distance from all nodes in a set
- Find distance between two nodes of a Binary Tree
- Iterative program to find distance of a node from root
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree
- Print path from root to all nodes in a Complete Binary Tree
- Count nodes having smallest value in the path from root to itself in a Binary Tree
- Count root to leaf paths having exactly K distinct nodes in a 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 email@example.com. 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.