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.
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 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
- Deepest right leaf node in a binary tree | Iterative approach
- Deepest left leaf node in a binary tree | iterative approach
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Check for Symmetric Binary Tree (Iterative Approach)
- Iterative approach to check if a Binary Tree is Perfect
- Iterative approach to check for children sum property in a Binary Tree
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Construct Binary Tree from given Parent Array representation | Iterative Approach
- Get Level of a node in a Binary Tree
- Depth of the deepest odd level node in Binary Tree
- Level Order Predecessor of a node in Binary Tree
- Level Order Successor of a node in Binary Tree
- Find the maximum node at a given level in a binary tree