VOOZH about

URL: https://www.geeksforgeeks.org/dsa/get-level-of-a-node-in-a-binary-tree/

⇱ Level of a Node in Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Level of a Node in Binary Tree

Last Updated : 23 Jul, 2025

Given a Binary Tree and a key, the task is to find the level of key in the Binary Tree.

Examples:

Input : key = 4

👁 ex-3


Output: 3
Explanation: The level of the key in above binary tree is 3.

Input : key = 10

👁 ex-3

Output: -1
Explanation: Key is not present in the above Binary tree.

[Expected Approach - 1] Using Recursion - O(n) Time and O(h) Space

The idea is to start from the root and level as 1. If the target matches with root's data, return level. Else recursively call for left and right subtrees with level as level + 1

Below is the implementation of the above approach: 


Output
3

Time Complexity: O(n), where n is the number of nodes in the binary tree.
Auxiliary Space: O(h), where h is height of binary tree.

[Expected Approach - 2] Using Level Order Traversal- O(n) Time and O(n) Space

The idea is to perform a level-order traversal and keep track of the current level as we traverse the tree. If the key matches with root's data, return level.


Output
3

Time Complexity: O(n), where n is the number of nodes in the binary tree.
Auxiliary Space: O(n)

Comment
Article Tags:
Article Tags: