Level of a Node in Binary Tree | Practice | GeeksforGeeks

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
0
ravikishan6242 months ago
JAVA Solution
 
Just an simple approach similar to preOrder traversal, in place of printing data we need to have variable (int) which can count the level that's it.
 
class Solution{     /* Returns level of given data value */
   int getLevel(Node node, int data)     {               return levelGet(node,data,1);          }       int levelGet(Node node, int data, int level){       if(node==null) return 0;       if(node.data==data) return level;       int downLevel=levelGet(node.left,data,level+1);       if(downLevel!=0) return downLevel;       downLevel=levelGet(node.right,data,level+1);       return downLevel;   }   
}
0
hamidnourashraf2 months ago
class Solution:
    def getLevel(self, root, target):
        
        level = 1 
        q = [(root, level)]
        while len(q) > 0:
            node, level = q.pop(0)
            if node.data == target:
                return level
            if node.left:
                q.append((node.left, level+1))
            if node.right:
                q.append((node.right, level+1))
        return 0
0
ishnoorsinghsethi3 months ago
C++ solution using Level Order Traversal
int getLevel(struct Node *node, int target)   {    int ans;    int level = 1;    queue<Node * > q;    q.push(node);    while(q.size()){        int count = q.size();        while(count--){            Node * p = q.front();            q.pop();            if(p->data == target) return level;            if(p->left) q.push(p->left);            if(p->right) q.push(p->right);        }        level++;    }    return 0;   }
0
abhishekvicky123453 months ago
/*Java Solution*/
class Solution{  public int flag=0;  public void check(Node root,int data,int level)  {      if(root.data==data)      flag=level;      if(root.left!=null)      check(root.left,data,level+1);      if(root.right!=null)      check(root.right,data,level+1);      }     public int getLevel(Node node, int data)     {       check(node,data,1);      return flag;   } }
0
shiva10903 months ago
 int ans = 0;
    void nodelevel(struct Node* root , int x , int level)
    {
        if(root == NULL)return;
        
        if(root->data == x){
            ans = level;
            return;
        }
        
        nodelevel(root->left , x , level+1);
        nodelevel(root->right , x , level+1);
    }
    int getLevel(struct Node *node, int target)
    {
    	//code here
    	nodelevel(node , target , 1);
    	return ans;
    }
0
mayank20213 months ago
C++ int getLevel(struct Node *node, int target)   {       if(node==NULL)        return 0;    else if(node->data==target)     return 1;    else if(getLevel(node->left, target) || getLevel(node->right, target))     return (1+max(getLevel(node->left, target), getLevel(node->right, target)));    else    return 0;       }
+1
codingprep213 months ago
JAVA

class Solution
{
    int getLevel(Node node, int data) {
        if (node == null) return 0;
        if (node.data == data) return 1;
        int result = getLevel(node.right, data);
        if (result == 0) {
            result = getLevel(node.left, data);
        }
        return result == 0 ? 0 : ++result;
    } 
}
0
snipperwolf3 months ago
class Solution:   def getLevel(self, root,target):       '''       :param root: root of given tree.       :param target: target to find level       :return:       LEVEL NO       '''       depth=1       l=[]       level(root,target,depth,l)       if len(l)==0:           return 0       else:           return l[-1]def level(root,target,depth,l):   if root is None:       return 0   if root.data==target:       l.append(depth)   level(root.left,target,depth+1,l)   level(root.right,target,depth+1,l)
0
emmanueluluabuike3 months ago
A simple java solution with explanations
int level = 0;
    int getLevel(Node node, int data){ 
        // The search begins from 1 because we are counting (root node) from 1
        return search(node, data, 1);
    }
    
    int search(Node node, int search, int h){
        // Checks if the initial is null or first root node is equal
        // to search, return level = 0
        if(node == null || (search == node.data && h == 0)) {
            return 0;
        }
        // Just like inOrder travesal, search nodes on the left, visit the root, 
        // and search nodes on right while incrementing the height
        // Whilst performing Inorder traversal, we checking each node data to see
        // if it is equal to search and then return the level
        search(node.left, search, h + 1);
        // And then checking each node to see it 
        if(node.data == search){
            level = h;
        }
        search(node.right, search, h + 1);
        return level;
    }
+1
17vineet3 months ago
int getLevel(Node node, int data)  
    {
        int level = 1 ;
        Queue<Node> q = new LinkedList<Node>() ;
        q.add(node) ;
        
        while(true)
        {
            int size = q.size() ;
            if(size == 0)
                break ;
            
            while(size>0)
            {
                Node root = q.poll() ;
                if(root.data == data)
                    return level ;
                
                if(root.left != null)
                    q.add(root.left) ;
                if(root.right != null)
                    q.add(root.right) ;
                    
                size-- ;
            }
            level++ ;
        }
        return 0 ;
    } 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.