1 test case failing pls help
1 test case is failing
hello @kunal81198
u have doubt in topview or bottom view of tree.
i m asking because ur code is of top view but u have raised it in bottom view.
pls confirm
@kunal81198
assuming u r trying bottom view.
ur code is correct , it is giving wa becuase there can be multiple valid solution but cb checker looks only for 1 valid solution .
for example->
/ \
\ /
here both leaves are at bottom but they are overlapping so there may be two valid solutions.
to pass cases follow this approac->
The idea is to create an empty map where each key represents the relative horizontal distance of the node from the root node and value in the map maintains a pair containing node’s value and its level number. Then we do a pre-order traversal of the tree and if current level of a node is more than or equal to maximum level seen so far for the same horizontal distance as current node’s or current horizontal distance is seen for the first time, we update the value and the level for current horizontal distance in the map. For each node, we recurse for its left subtree by decreasing horizontal distance and increasing level by 1 and recurse for right subtree by increasing both.
void bottomViewHelper(node *root, int level, int dist, map<int, pair<int, int> > &mp) {
if(root == NULL) {
return;
}
if(mp.find(dist) == mp.end() or level>=mp[dist].second) {
mp[dist] = {root->data, level};
}
bottomViewHelper(root->left, level+1, dist-1, mp);
bottomViewHelper(root->right, level+1, dist+1, mp);
}
void bottomView(node *root)
{
map<int, pair<int, int> >mp;
bottomViewHelper(root, 0, 0, mp);
for(auto val:mp){
cout<<val.second.first<<" ";
}
}
hey i cant understand in question it says if 2 nodes are overlapping and at same level then print the right one and i am printing the last index of vector so whats the problem here
@kunal81198
check ur code for this input->
20 8 22 5 3 4 25 -1 -1 10 14 -1 -1 -1 -1 -1 -1 -1 -1
expected output->
5 10 4 14 25
mp.find(dist) == mp.end() this condition is for initial input right?
this is checking whether dist is there in the map of not
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.