one test case is not passing
my code is
void rightView1(node *root, int level, int dist, map<int, pair<int, int> > &mp) {
if(root == NULL) {
return;
}
if(mp.find(level) == mp.end() or dist>=mp[level].second) {
mp[level] = {root->data, dist};
}
// cout<data<<" “<<dist<<” “<<level<<endl;
rightView1(root->left, level+1, dist-1, mp);
rightView1(root->right, level+1, dist+1, mp);
}
void rightView(node *root)
{
map<int, pair<int, int> >mp;
rightView1(root, 0, 0, mp);
for(auto val:mp){
cout<<val.second.first<<” ";
}
}
Tree right view
@Chitra_Singla Your code is not able to print all the nodes on the right.
Consider the case:
55 88 28 80 89 45 30 101 -1 90 -1 56 -1 -1 -1 -1 -1 99 -1 -1 -1 -1 -1
Output should be:
55 28 30 56 99
To correct this you can take a variable for level and for every next level you can print the rightmost node of that level.You can check for this input .
If still you are unable to get the idea of passing level to the function you can refer this code snippet.
void rightViewHelper(node *root, int level, int &max_level) {
if(root == NULL) {
return;
}
if(max_level<level) {
cout<data<<" ";
max_level = level;
}
rightViewHelper(root->right, level+1, max_level);
rightViewHelper(root->left, level+1, max_level);
}
void rightView(node *root) {
int max_level = 0;
rightViewHelper(root, 1, max_level);
}
using this code snippet, the ans is still not correct
correct ans is : 55 28 30 56 99
but the output coming is : 55 28 30 99