-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNode Level.cpp
More file actions
42 lines (37 loc) · 858 Bytes
/
Node Level.cpp
File metadata and controls
42 lines (37 loc) · 858 Bytes
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
#include <bits/stdc++.h>
using namespace std;
template <typename T>
class TreeNode
{
public:
T val;
bool isOriginal;
TreeNode<T> *left;
TreeNode<T> *right;
TreeNode(T val)
{
this->val = val;
left = NULL;
right = NULL;
}
};
int nodeLevel(TreeNode<int> *root, int searchedValue)
{
// Write your code here.
queue<pair<TreeNode<int> *, int>> q;
// q.push(make_pair(root, 1));
q.push({root, 1});
while (!q.empty())
{
pair<TreeNode<int> *, int> parent = q.front();
TreeNode<int> *node = parent.first;
int level = parent.second;
q.pop();
if (node->val == searchedValue)
return level;
if (node->left)
q.push({node->left, level + 1});
if (node->right)
q.push({node->right, level + 1});
}
}