Given the root of a binary tree and a key x in it, find the distance of the given key from the root node. Distance means number of edges between two nodes.
Input : x = 45, 5 is 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.
Related Problem: Recursive program to find distance of node from root.
Iterative Approach :
- Use level order traversal to traverse the tree iteratively using a queue.
- Keep a variable levelCount to maintain the track of current level.
- To do this, every time on moving to the next level, while pushing a NULL node to the queue also increment the value of the variable levelCount so that it stores the current level number.
- While traversing the tree, check if any node at the current level matches with the given key.
- If yes, then return levelCount.
Below is the implementation of above approach:
- Find distance from root to given node in a binary tree
- Print nodes at k distance from root | Iterative
- Find root of the tree where children id sum for every node is given
- Print nodes at k distance from root
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Check if two nodes are in same subtree of the root node
- Get level of a node in binary tree | iterative approach
- Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)
- Print path from root to a given node in a binary tree
- Sum of nodes on the longest path from root to leaf node
- Sort the path from root to a given node in a Binary Tree
- Deepest right leaf node in a binary tree | Iterative approach
- Print all nodes at distance k from a given node
- Iterative Segment Tree (Range Maximum Query with Node Update)
- Deepest left leaf node in a binary tree | iterative approach
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.