Given root of a binary tree and a key x in it, find distance of the given key from root. Distance means number of edges between two nodes.
Input : x = 45, Root of below tree 5 / \ 10 15 / \ / \ 20 25 30 35 \ 45 Output : Distance = 3 There are three edges on path from root to 45. For more understanding of question, in above tree distance of 35 is two and distance of 10 is 1.
The idea is to traverse the tree from root. Check if x is present at root or in left subtree or in right subtree. We initialize distance as -1 and add 1 to distance for all three cases.
This article is contributed by Roshni Agarwal. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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.
- Iterative program to find distance of a node from root
- Find distance of nodes from root in a tree for multiple queries
- Print path from root to a given node in a binary tree
- Sort the path from root to a given node in a Binary Tree
- Queries to find sum of distance of a given node to every leaf node in a Weighted Tree
- Distance between two nodes of binary tree with node values from 1 to N
- Find root of the tree where children id sum for every node is given
- Find all root to leaf path sum of a Binary Tree
- Find maximum GCD value from root to leaf in a Binary tree
- Find the maximum sum leaf to root path in a Binary Tree
- Find distance between two nodes of a Binary Tree
- 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 the parent of a node in the given binary tree
- Find the Deepest Node in a Binary Tree
- Find mirror of a given node in Binary tree
- Find the node with maximum value in a Binary Search Tree
- Find the Deepest Node in a Binary Tree Using Queue STL - SET 2
- Find the node with minimum value in a Binary Search Tree