How to find level of a node in Binary Tree in Java

We will learn how to find out the level of a given node in binary tree in Java. We will search for the key in binary tree. The level of the root is 1. If we do not find the key in binary tree then its level will be given as 0.
The following are the steps to get the level of a node in binary tree:

  1. If the node is null, then we return 0.
  2. If node’s data value is equal to the key, then return level.
  3. We recursively search for the key in left subtree.
  4. If key not found, we recursively search in right subtree.

Java Code to find Node Level (Recursion) in  a binary tree:

static int getLevel(Node root,int key,int level)
  {
    if(root==null)
      return 0;
    if(root.data==key)
      return level;
 
    int result=getLevel(root.left,key,level+1) ;
    if(result!=0)
      return result;
    result= getLevel(root.right,key,level+1);

    return result;
  }

We will use the above-given method to get the level of the node via recursion if its data matches the key value. Below given is the entire java program to perform this operation using this method.

Java program:

class Main {
 
  public static class Node
  {
    int data;
    Node left;
    Node right;
    Node(int data)
    {
      this.data=data;
    }
  }
  public static int getLevel(Node root,int key,int level)
  {
    if(root==null)
      return 0;
    if(root.data==key)
      return level;
 
    int result=getLevel(root.left,key,level+1) ;
    if(result!=0)
      return result;

    result= getLevel(root.right,key,level+1);
 
    return result;
  }
 
 
  public static void main(String[] args)
  {
    Node root=createBinaryTree();
    System.out.println("Node: 79,Level :"+getLevel(root, 79, 1));
    System.out.println("Node: 10,Level :"+getLevel(root, 90, 1));
    System.out.println("Node: 50,Level :"+getLevel(root, 50, 1));
    System.out.println("Node: 40,Level :"+getLevel(root, 40, 1));
  }
 
  public static Node createBinaryTree()
  {
 
    Node root =new Node(40);
          Node node20=new Node(20);
    Node node10=new Node(10);
    Node node30=new Node(30);
    Node node55=new Node(55);
    Node node50=new Node(50);
    Node node79=new Node(79);
 
    root.left=node20;
    root.right=node55;
 
    node20.left=node10;
    node20.right=node30;
 
    node55.left=node50;
    node55.right=node79;
 
    return root;
  }
}

 

Output:

Node: 79,Level :3
Node: 10,Level :0
Node: 50,Level :3
Node: 40,Level :1

 

Also read,

Leave a Reply

Your email address will not be published. Required fields are marked *