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.
- Queries to find sum of distance of a given node to every leaf node in a Weighted Tree
- Iterative program to find distance of a node from root
- Find node U containing all nodes from a set V at atmost distance 1 from the path from root to U
- 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
- Find distance of nodes from root in a tree for multiple queries
- Find root of the tree where children id sum for every node is given
- Maximum XOR with given value in the path from root to given node in the tree
- Farthest distance of a Node from each Node of a Tree
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Distance between two nodes of binary tree with node values from 1 to N
- Find distance between two nodes in the given Binary tree for Q queries
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Find the maximum sum leaf to root path in a Binary Tree
- Find maximum GCD value from root to leaf in a Binary tree
- Find all root to leaf path sum of a Binary Tree
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Given a binary tree, print all root-to-leaf paths
- Count the number of paths from root to leaf of a Binary tree with given XOR value
- Find parent of given node in a Binary Tree with given postorder traversal