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 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.
- Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
- Iterative Approach to check if two Binary Trees are Isomorphic or not
- Level Order Predecessor of a node in Binary Tree
- Level Order Successor of a node in Binary Tree
- Print all nodes except rightmost node of every level of the Binary Tree
- Deletion of a given node K in a Binary Tree using Level Order Traversal
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Check if max sum level of Binary tree divides tree into two equal sum halves
- Iterative Method To Print Left View of a Binary Tree
- Connect Nodes at same Level (Level Order Traversal)
- General Tree (Each node can have arbitrary number of children) Level Order Traversal
- Print nodes between two given level numbers of a binary tree
- Perfect Binary Tree Specific Level Order Traversal
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Perfect Binary Tree Specific Level Order Traversal | Set 2
- Print extreme nodes of each level of Binary Tree in alternate order
- Find maximum level sum in Binary Tree
- Print odd positioned nodes of odd levels in level order of the given binary tree
- Construct a complete binary tree from given array in level order fashion