-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathlevel_of_node.cpp
More file actions
84 lines (68 loc) · 1.15 KB
/
Copy pathlevel_of_node.cpp
File metadata and controls
84 lines (68 loc) · 1.15 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include<iostream>
#include<queue>
using namespace std;
struct node{
int data;
node *left;
node *right;
node(int k)
{
data=k;
left=NULL;
right=NULL;
}
};
node* addnode()
{
queue<node*> q;
int n,k;
node* root;
cout<<"enter the number of nodes";
cin>>n; //n defines the number of nodes
while(n--)
{
cin>>k; //data value of the node
node* a = new node(k);
if(!q.empty())
{
if(q.front()->left==NULL)
{
q.front()->left=a;
}
else if(q.front()->right==NULL)
{
q.front()->right=a;
q.pop();
}
}
else
{
root=a;
}
q.push(a);
}
return root;
}
int find_level(node* root,int k)
{
if(root==NULL)
return -1;
if(root->data == k)
return 0;
int l = find_level(root->left,k);
if(l>=0)
return l+1;
int r = find_level(root->right,k);
if(r>=0)
return r+1;
return r;
}
int main()
{
int k;
node * root = addnode();
cout<<"enter the key of the node";
cin>>k;
cout<<find_level(root,k);
return 0;
}