-
Notifications
You must be signed in to change notification settings - Fork 1
/
Bheem_Wants_Ladoos.cpp
75 lines (75 loc) · 1.66 KB
/
Bheem_Wants_Ladoos.cpp
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
class Solution{
public:
Node *king;
unordered_map<Node *, Node *> parent;
int LevelOrder(int k)
{
int sum = 0;
queue<Node *> q;
q.push(king);
unordered_map<Node *, bool> vis;
vis[king] = true;
int steps = 0;
while (!q.empty())
{
int qsize = q.size();
while (qsize--)
{
auto curr = q.front();
q.pop();
sum += curr->data;
if (curr->left && !vis[curr->left])
{
vis[curr->left] = true;
q.push(curr->left);
}
if (curr->right && !vis[curr->right])
{
vis[curr->right] = true;
q.push(curr->right);
}
if (parent[curr] && !vis[parent[curr]])
{
vis[parent[curr]] = true;
q.push(parent[curr]);
}
}
if (steps == k)
break;
steps++;
}
return sum;
}
// Find the home and make the parent map
void MakeParent(Node *root, int home)
{
queue<Node *> q;
q.push(root);
parent[root] = NULL;
while (!q.empty())
{
auto curr = q.front();
q.pop();
// Searching the home
if (curr->data == home)
{
king = curr;
}
if (curr->left)
{
q.push(curr->left);
parent[curr->left] = curr;
}
if (curr->right)
{
q.push(curr->right);
parent[curr->right] = curr;
}
}
}
int ladoos(Node *root, int home, int k)
{
MakeParent(root, home);
return LevelOrder(k);
}
};