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++
// C++ program to Get Level of a node in a Binary Tree
#include <bits/stdc++.h>
usingnamespacestd;
/* A tree node structure */
structnode {
intdata;
structnode* left;
structnode* right;
};
// Helper function for getLevel(). It returns level of the
// data if data is present in tree, otherwise returns 0.
// This code is contributed by Aditya Kumar (adityakumar129)
Python3
# Python3 program to print level in which X is present in
# binary tree
# A node structure
classNode:
# A utility function to create a new node
def__init__(self, key):
self.data =key
self.left =None
self.right =None
defprintLevel(root, X):
# Base Case
ifroot isNone:
return0
# Create an empty queue
# for level order traversal
q =[]
#Create a var represent current level of tree
currLevel =1
# Enqueue Root
q.append(root)
while(len(q) > 0):
size =len(q)
fori inrange(size):
node =q.pop(0)
if(node.data ==X):
returncurrLevel
# Enqueue left child
ifnode.left isnotNone:
q.append(node.left)
# Enqueue right child
ifnode.right isnotNone:
q.append(node.right)
currLevel +=1
return0
# Driver Program to test above function
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))
# This code is contributed by Abhijeet Kumar(abhijeet19403)
C#
// C# program to print level in which X is present in
// binary tree
usingSystem;
usingSystem.Collections.Generic;
/* Class to represent Tree node */
publicclassNode {
publicintdata;
publicNode left, right;
publicNode(intitem)
{
data = item;
left = null;
right = null;
}
}
/* Class to print Level Order Traversal */
publicclassBinaryTree {
Node root;
/* Function to get the level of the node X*/
intprintLevel(intX)
{
Node node;
// Base Case
if(root == null)
return0;
// Create an empty queue for level order traversal
Queue<Node> q = newQueue<Node>();
// Create a var represent current level of tree
intcurrLevel = 1;
// Enqueue root
q.Enqueue(root);
while(q.Count != 0) {
intsize = q.Count;
while(size-- != 0) {
node = q.Dequeue();
if(node.data == X)
returncurrLevel;
/*Enqueue left child */
if(node.left != null)
q.Enqueue(node.left);
/*Enqueue right child */
if(node.right != null)
q.Enqueue(node.right);
}
currLevel++;
}
return0;
}
// Driver code
publicstaticvoidMain()
{
/* creating a binary tree and entering
the nodes */
BinaryTree tree_level = newBinaryTree();
tree_level.root = newNode(1);
tree_level.root.left = newNode(2);
tree_level.root.right = newNode(3);
tree_level.root.left.left = newNode(4);
tree_level.root.left.right = newNode(5);
tree_level.root.right.left = newNode(7);
tree_level.root.right.right = newNode(6);
Console.WriteLine(tree_level.printLevel(6));
}
}
/* This code contributed by Abhijeet Kumar(abhijeet19403) */
Javascript
// JavaScript program to print level in which X is present in
// binary tree
class Node
{
constructor(d) {
this.data = d;
this.left = null;
this.right = null;
}
}
let root;
// Given a binary tree. Print its nodes in level order
// using array for implementing queue.
// Create a var represent current level of tree
let currLevel = 1;
functionprintLevelOrder(X){
// Create an empty queue for level order traversal
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){
returncurrLevel;
}
/*Enqueue left child */
if(tempNode.left){
queue.push(tempNode.left);
}
/*Enqueue right child */
if(tempNode.right){
queue.push(tempNode.right);
}
}
currLevel+=1;
}
returnroot.data;
}
/* creating a binary tree and entering
the nodes */
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);
console.log(printLevelOrder(6));
// This code is contributed by lokeshmvs21.
Output
3
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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!