Get Level of a node in a Binary Tree | GeeksforGeeks
Given a Binary Tree and a key, write a function that returns level of the key.
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.
Read full article from Get Level of a node in a Binary Tree | GeeksforGeeks
Given a Binary Tree and a key, write a function that returns level of the key.
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.
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;
}
/* Returns level of given data value */
int
getLevel(
struct
node *node,
int
data)
{
return
getLevelUtil(node,data,1);
}