C++ soln using recursion and multimap


#1

void mapit(bool &cond,TreeNode* root,int t,int level,int &reqlev,unordered_multimap <int,int> &m){
if(root==NULL or (cond and reqlev<level))
return;
if(root->left!=NULL and root->right!=NULL)
{
if(root->left->val==t or root->right->val==t){
cond=true;
reqlev=level+1;
return;
}
}
if(root->val==t){
cond=true;
reqlev=level;
return;
}
m.insert({level,root->val});
mapit(cond,root->left,t,level+1,reqlev,m);
mapit(cond,root->right,t,level+1,reqlev,m);
}
vector Solution::solve(TreeNode* A, int b) {
unordered_multimap<int,int> m;
int req=0;
bool cond=false;
mapit(cond,A,b,1,req,m);
vector ans;
auto itr=m.equal_range(req);
for(auto i=itr.first;i!=itr.second;i++)
ans.push_back(i->second);
return ans;
}