-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlevel.c
executable file
·67 lines (54 loc) · 1.47 KB
/
level.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<stdio.h>
#include<stdlib.h>
/* A tree node structure */
struct node
{
int data;
struct node *left;
struct node *right;
};
/*
* Helper function for getLevel(). It returns level of the data if data is
* present in tree, otherwise returns 0.
* */
int getLevelUtil(struct node *node, int data, int level)
{
if ( node == NULL )
return 0;
if ( node->data == data )
return level;
return getLevelUtil ( node->left, data, level+1) |
getLevelUtil ( node->right, data, level+1);
}
/* Returns level of given data value */
int getLevel(struct node *node, int data)
{
return getLevelUtil(node,data,1);
}
/* Utility function to create a new Binary Tree node */
struct node* newNode(int data)
{
struct node *temp = new struct node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
/* Driver function to test above functions */
int main()
{
struct node *root = new struct node;
int x;
/* Constructing tree given in the above figure */
root = newNode(3);
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(1);
root->left->right = newNode(4);
x = 3;
printf(" Level of %d is %d", x, getLevel(root, x));
x = 6;
printf("\n Level of %d is %d", x, getLevel(root, x));
getchar();
return 0;
}