Get level of a node in binary tree | iterative approach
Given a Binary Tree and a key, write a function that returns level of the key.
For example, consider the following tree. If the input key is 3, then your function should return 1. If the input key is 4, then your function should return 3. And for key which is not present in key, then your function should return 0.
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Recursive approach to this problem is discussed here
The iterative approach is discussed below :
The iterative approach is modified version of Level Order Tree Traversal
create a empty queue q push root and then NULL to q loop till q is not empty get the front node into temp node if it is NULL, it means all nodes of one level are traversed, so increment level else check if temp data is equal to data to be searched if yes then return level if temp->left is not NULL, enqueue temp->left if temp->right is not NULL, enqueue temp->right if value not found, then return 0
level of node 30 is 2 level of node 12 is 4 level of node 25 is 3 node 27 not found
This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. 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.