The best programs are written so that computing machines can perform
them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist
who works with traditional aesthetic and literary forms as well as mathematical concepts, to
communicate the way that an algorithm works and to convince a reader that the results will be correct.
― Donald E. Knuth

Problem :-
Implement an algorithm to get the level of a node in a Binary Tree assuming root node to be at level 1.
For e.g, for the tree shown below, level of node 24 is 3 .

Solution :-
We will recursively traverse the left and right subtrees till we find the given node. While traversing, we maintain the level
information and return the level when we encounter the input node. The root node is at level 1 and then
level for recursive calls to subtrees is incremented by 1. See the implementation below.

#include<iostream>using namespace std;
typedef struct node {
int value;
struct node *left, *right;
}node;
// create a new node
node *getNewNode(int value) {
node *new_node = new node;
new_node->value = value;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
// get the level of the node
// root node is assumed to be at level 1int getLevel(node *ptr,int val,int level) {
if (ptr == NULL)
return 0;
if (ptr->value == val)
return level;
return getLevel(ptr->left, val, level+1) | getLevel(ptr->right, val, level+1);
}
// create the tree
node *createTree() {
node *root = getNewNode(31);
root->left = getNewNode(16);
root->right = getNewNode(52);
root->left->left = getNewNode(7);
root->left->right = getNewNode(24);
root->left->right->left = getNewNode(19);
root->left->right->right = getNewNode(29);
return root;
}
// mainint main() {
node *root = createTree();
int val = 24;
int level = getLevel(root,val,1);
cout<<"\nLevel of "<<val<<" is "<<level<<endl;
return 0;
}

#include<iostream>using namespace std;
typedef struct node {
int value;
struct node *left, *right;
}node;
// create a new node
node *getNewNode(int value) {
node *new_node = new node;
new_node->value = value;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
// get the level of the node
// root node is assumed to be at level 1int getLevel(node *ptr,int val,int level) {
if (ptr == NULL)
return 0;
if (ptr->value == val)
return level;
return getLevel(ptr->left, val, level+1) | getLevel(ptr->right, val, level+1);
}
// create the tree
node *createTree() {
node *root = getNewNode(31);
root->left = getNewNode(16);
root->right = getNewNode(52);
root->left->left = getNewNode(7);
root->left->right = getNewNode(24);
root->left->right->left = getNewNode(19);
root->left->right->right = getNewNode(29);
return root;
}
// mainint main() {
node *root = createTree();
int val = 24;
int level = getLevel(root,val,1);
cout<<"\nLevel of "<<val<<" is "<<level<<endl;
return 0;
}