Get Level of a node in a Binary Tree
Last Updated :
21 Nov, 2022
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.
The idea is to start from the root and level as 1. If the key matches with root’s data, return level. Else recursively call for left and right subtrees with level as level + 1.
C++
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
struct node* left;
struct node* right;
};
int getLevelUtil( struct node* node, int data, int level)
{
if (node == NULL)
return 0;
if (node->data == data)
return level;
int downlevel
= getLevelUtil(node->left, data, level + 1);
if (downlevel != 0)
return downlevel;
downlevel = getLevelUtil(node->right, data, level + 1);
return downlevel;
}
int getLevel( struct node* node, int data)
{
return getLevelUtil(node, data, 1);
}
struct node* newNode( int data)
{
struct node* temp = new struct node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
int main()
{
struct node* root = new struct node;
int x;
root = newNode(3);
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(1);
root->left->right = newNode(4);
for (x = 1; x <= 5; x++) {
int level = getLevel(root, x);
if (level)
cout << "Level of " << x << " is " << level
<< endl;
else
cout << x << "is not present in tree" << endl;
}
getchar ();
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* left;
struct node* right;
} node;
int getLevelUtil(node* node, int data, int level)
{
if (node == NULL)
return 0;
if (node->data == data)
return level;
int downlevel
= getLevelUtil(node->left, data, level + 1);
if (downlevel != 0)
return downlevel;
downlevel = getLevelUtil(node->right, data, level + 1);
return downlevel;
}
int getLevel(node* node, int data)
{
return getLevelUtil(node, data, 1);
}
node* newNode( int data)
{
node* temp = (node*) malloc ( sizeof (node));
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
int main()
{
node* root;
int x;
root = newNode(3);
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(1);
root->left->right = newNode(4);
for (x = 1; x <= 5; x++) {
int level = getLevel(root, x);
if (level)
printf ( " Level of %d is %d\n" , x,
getLevel(root, x));
else
printf ( " %d is not present in tree \n" , x);
}
getchar ();
return 0;
}
|
Java
class Node {
int data;
Node left, right;
public Node( int d)
{
data = d;
left = right = null ;
}
}
class BinaryTree {
Node root;
int getLevelUtil(Node node, int data, int level)
{
if (node == null )
return 0 ;
if (node.data == data)
return level;
int downlevel
= getLevelUtil(node.left, data, level + 1 );
if (downlevel != 0 )
return downlevel;
downlevel
= getLevelUtil(node.right, data, level + 1 );
return downlevel;
}
int getLevel(Node node, int data)
{
return getLevelUtil(node, data, 1 );
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node( 3 );
tree.root.left = new Node( 2 );
tree.root.right = new Node( 5 );
tree.root.left.left = new Node( 1 );
tree.root.left.right = new Node( 4 );
for ( int x = 1 ; x <= 5 ; x++) {
int level = tree.getLevel(tree.root, x);
if (level != 0 )
System.out.println(
"Level of " + x + " is "
+ tree.getLevel(tree.root, x));
else
System.out.println(
x + " is not present in tree" );
}
}
}
|
Python3
class newNode:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def getLevelUtil(node, data, level):
if (node = = None ):
return 0
if (node.data = = data):
return level
downlevel = getLevelUtil(node.left,
data, level + 1 )
if (downlevel ! = 0 ):
return downlevel
downlevel = getLevelUtil(node.right,
data, level + 1 )
return downlevel
def getLevel(node, data):
return getLevelUtil(node, data, 1 )
if __name__ = = '__main__' :
root = newNode( 3 )
root.left = newNode( 2 )
root.right = newNode( 5 )
root.left.left = newNode( 1 )
root.left.right = newNode( 4 )
for x in range ( 1 , 6 ):
level = getLevel(root, x)
if (level):
print ( "Level of" , x,
"is" , getLevel(root, x))
else :
print (x, "is not present in tree" )
|
C#
using System;
public class Node {
public int data;
public Node left, right;
public Node( int d)
{
data = d;
left = right = null ;
}
}
public class BinaryTree {
public Node root;
public virtual int getLevelUtil(Node node, int data,
int level)
{
if (node == null ) {
return 0;
}
if (node.data == data) {
return level;
}
int downlevel
= getLevelUtil(node.left, data, level + 1);
if (downlevel != 0) {
return downlevel;
}
downlevel
= getLevelUtil(node.right, data, level + 1);
return downlevel;
}
public virtual int getLevel(Node node, int data)
{
return getLevelUtil(node, data, 1);
}
public static void Main( string [] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(3);
tree.root.left = new Node(2);
tree.root.right = new Node(5);
tree.root.left.left = new Node(1);
tree.root.left.right = new Node(4);
for ( int x = 1; x <= 5; x++) {
int level = tree.getLevel(tree.root, x);
if (level != 0) {
Console.WriteLine(
"Level of " + x + " is "
+ tree.getLevel(tree.root, x));
}
else {
Console.WriteLine(
x + " is not present in tree" );
}
}
}
}
|
Javascript
<script>
class Node
{
constructor(d) {
this .data = d;
this .left = null ;
this .right = null ;
}
}
let root;
function getLevelUtil(node, data, level)
{
if (node == null )
return 0;
if (node.data == data)
return level;
let downlevel
= getLevelUtil(node.left, data, level + 1);
if (downlevel != 0)
return downlevel;
downlevel
= getLevelUtil(node.right, data, level + 1);
return downlevel;
}
function getLevel(node, data)
{
return getLevelUtil(node, data, 1);
}
root = new Node(3);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(4);
for (let x = 1; x <= 5; x++)
{
let level = getLevel(root, x);
if (level != 0)
document.write(
"Level of " + x + " is "
+ getLevel(root, x) + "</br>" );
else
document.write(
x + " is not present in tree" );
}
</script>
|
Output
Level of 1 is 3
Level of 2 is 2
Level of 3 is 1
Level of 4 is 3
Level of 5 is 2
Time Complexity: O(n) where n is the number of nodes in the given Binary Tree.
Auxiliary Space: O(n)
Alternative Approach: The given problem can be solved with the help of level order traversal of given binary tree.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
int printLevel(Node* root, int X)
{
Node* node;
if (root == NULL)
return 0;
queue<Node*> q;
int currLevel = 1;
q.push(root);
while (q.empty() == false ) {
int size = q.size();
while (size--) {
node = q.front();
if (node->data == X)
return currLevel;
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
}
currLevel++;
}
return 0;
}
Node* newNode( int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(7);
root->right->right = newNode(6);
cout << printLevel(root, 6);
return 0;
}
|
Java
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
public Node( int item)
{
data = item;
left = null ;
right = null ;
}
}
class BinaryTree {
Node root;
public static int currLevel = 1 ;
int printLevelOrder( int X)
{
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
for ( int i = 0 ; i < size; i++) {
Node tempNode = queue.poll();
if (tempNode.data == X)
return currLevel;
if (tempNode.left != null )
queue.add(tempNode.left);
if (tempNode.right != null )
queue.add(tempNode.right);
}
currLevel++;
}
return currLevel;
}
public static void main(String args[])
{
BinaryTree tree_level = new BinaryTree();
tree_level.root = new Node( 1 );
tree_level.root.left = new Node( 2 );
tree_level.root.right = new Node( 3 );
tree_level.root.left.left = new Node( 4 );
tree_level.root.left.right = new Node( 5 );
tree_level.root.right.left = new Node( 7 );
tree_level.root.right.right = new Node( 6 );
System.out.println(
"Level order traversal of binary tree is - "
+ tree_level.printLevelOrder( 6 ));
}
}
|
Python3
class Node:
def __init__( self , key):
self .data = key
self .left = None
self .right = None
def printLevel(root, X):
if root is None :
return 0
q = []
currLevel = 1
q.append(root)
while ( len (q) > 0 ):
size = len (q)
for i in range (size):
node = q.pop( 0 )
if (node.data = = X):
return currLevel
if node.left is not None :
q.append(node.left)
if node.right is not None :
q.append(node.right)
currLevel + = 1
return 0
root = Node( 1 )
root.left = Node( 2 )
root.right = Node( 3 )
root.left.left = Node( 4 )
root.left.right = Node( 5 )
root.right.left = Node( 7 )
root.right.right = Node( 6 )
print (printLevel(root, 6 ))
|
C#
using System;
using System.Collections.Generic;
public class Node {
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = null ;
right = null ;
}
}
public class BinaryTree {
Node root;
int printLevel( int X)
{
Node node;
if (root == null )
return 0;
Queue<Node> q = new Queue<Node>();
int currLevel = 1;
q.Enqueue(root);
while (q.Count != 0) {
int size = q.Count;
while (size-- != 0) {
node = q.Dequeue();
if (node.data == X)
return currLevel;
if (node.left != null )
q.Enqueue(node.left);
if (node.right != null )
q.Enqueue(node.right);
}
currLevel++;
}
return 0;
}
public static void Main()
{
BinaryTree tree_level = new BinaryTree();
tree_level.root = new Node(1);
tree_level.root.left = new Node(2);
tree_level.root.right = new Node(3);
tree_level.root.left.left = new Node(4);
tree_level.root.left.right = new Node(5);
tree_level.root.right.left = new Node(7);
tree_level.root.right.right = new Node(6);
Console.WriteLine(tree_level.printLevel(6));
}
}
|
Javascript
class Node
{
constructor(d) {
this .data = d;
this .left = null ;
this .right = null ;
}
}
let root;
let currLevel = 1;
function printLevelOrder(X){
let queue = [root];
while (queue[0]){
let size = queue.length;
for (let i=0;i<size;i++){
let tempNode = queue.shift();
if (tempNode.data==X){
return currLevel;
}
if (tempNode.left){
queue.push(tempNode.left);
}
if (tempNode.right){
queue.push(tempNode.right);
}
}
currLevel+=1;
}
return root.data;
}
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(7);
root.right.right = new Node(6);
console.log(printLevelOrder(6));
|
Time Complexity: O(n) where n is the number of nodes in the binary tree.
Auxiliary Space: O(n) where n is the number of nodes in the binary tree.
Please Login to comment...