Level of a Node in Binary Tree
Easy Accuracy: 50.02% Submissions: 17398 Points: 2

Given a Binary Tree and a target key you need to find the level of target key in the given Binary Tree.

Note: The level of the root node is 1.

           3
         /   \
        2     5
      /   \
     1     4
Key: 4
Level: 3  

Note: if no such key exists then return 0.

Example 1:

Input:
        1
      /   \
     2     3
target = 4
Output: 0

Example 2:

Input:
         3
       /   \
      2     5
    /   \
   1     4
target = 4
Output: 3

Your Task:
 You don't have to take input. Just complete the function getLevel() that takes a node and a target as parameters and returns the level of the target value. 

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(H).
Note: H is the height of the tree and this space is used implicitly for recursion stack.

Constraints:
1 <= Number of nodes<= 105
1 <= Data of a node<= 105
1 <= Target <= 105

We are replacing the old Disqus forum with the new Discussions section given below.
Click here to view old Disqus comments.


to report an issue on this page.

Editorial

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

Yes

All Submissions

My Submissions:

Login to access your submissions.

Level of a Node in Binary Tree

Output Window