-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bheem Wants Ladoos
49 lines (47 loc) · 1.27 KB
/
Bheem Wants Ladoos
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
class Solution{
void solve(Node *curr,Node* parent,unordered_map<Node*, Node*>&m){
if(curr==NULL)return;
m[curr]=parent;
solve(curr->left,curr,m);
solve(curr->right,curr,m);
return;
}
public:
Node * targets=NULL;
void solve1(Node* root, int &target){
if(root==NULL)return;
if(root->data==target){
targets=root;
}
solve1(root->left,target);
solve1(root->right,target);
return;
}
void distance(Node *root,int k,set<Node*>&s,unordered_map<Node* , Node*>&m,vector<int>&ans){
if(k<0 || s.find(root)!=s.end() || root==NULL)return;
s.insert(root);
ans.push_back(root->data);
if(k==0){
return;
}
distance(root->left,k-1,s,m,ans);
distance(root->right,k-1,s,m,ans);
distance(m[root],k-1,s,m,ans);
return;
}
int ladoos(Node* root, int home, int k)
{
// Your code goes here
unordered_map<Node*, Node*>m;
solve(root,NULL,m);
set<Node*>vis;
solve1(root,home);
vector<int>ans;
int sum=0;
distance(targets,k,vis,m,ans);
for(int i=0;i<ans.size();i++){
sum+=ans[i];
}
return sum;
}
};