Tree left view-1 test case wrong ans


whats wrong in my code???

your call on right subtree should be only when there is no left child, plus u need to take care of height, in your code the recurrence will print both left and right since the call and condition both are true for printing but for left view u need to use bfs technique

void left_view(node*root,int level){
if(root==NULL){
return;
}
static int max_level=0;

if(max_level<level){
    cout<<root->data<<" ";
    max_level=level;
}
left_view(root->left,level+1);
left_view(root->right,level+1);

}
well in this code it is checking for first left child then right child. you can dry run this

and while submitting your code it is showing run error in all cases…???

you do not need to go on the right child at all if the left child exists, since the left child is the only that needs to be checked for the left view

i am not going to right child, the function is just checking if left child exist then level will inc by 1 and hence the max_level too and it will not go the right child.

have you tried to dry run my code???

it goes in the stack call, it does not print however, on the other thread i mentioned that the answer for the test case is correct but it is probably due to time limit that the test case might be failing, try the bfs method, recursive approaches are not very time friendly, it makes an unnecessary call is all i am saying, other thing u could try is keep a check, ur stack call will be avoided, maybe i wasn’t clear enough, i hope this clears your doubt

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.