Can you tell what is wrong in this method?
Sir, now also one test case is not passing.
yeah its becuase if there more than one nodes at level horizontal and vertical level then we need to consider node that occurs in right.
here in ur code u are not handling it thats why it is failing.
example->
20 8 22 5 3 4 25 -1 -1 10 14 -1 -1 -1 -1 -1 -1 -1 -1
expected ->
5 10 4 14 25
urs->
5 10 4 22 25
and to pass all test cases u need to consider both horizontal and vertical level
sir, I am not able to resolve this issue
consider horizonatal and vertical distance both .
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 level and horizontal distance by 1.
code for reference->
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<<" ";
}
}