When talking about binary trees then the view of a binary tree is something that has the most probability to be asked in a coding interview.
In this blog post, I'm going to talk mainly about the Right & Left views of a binary tree.
There are so many ways available on the internet, that it's really a very difficult task to choose which method you should follow. Suppose, you're using one method for Left View and another method for Right View, now you need to know two different methods for two similar questions. In this blog we'll discuss a single approach by which you can solve both Left View and Right View problems.
Before diving directly into the approach we need to understand what exactly is this Right/Left view.
For your better understanding I've created a binary tree :
So, from the right side at level 0 we can see 1, at level 1 we can see 3 from the right side, and also 2 is being overlapped by 3 so we can't include it in our right view. Similarly, at level 2 we can see 5 and at level 3 we see 6.
So the nodes included in Right View are: 1, 3, 5, 6
Similarly, nodes included in Left View are: 1, 2, 4, 6
"So, it won't be wrong to say the node that appears for the first time at a given view level will be included in that particular view."
Implementing the above-mentioned approach :
Right View
// utility function
void right_view_func(node *root,int *level,int max_level)
{
if(root==NULL)
return ;
if(*level<max_level)
{
cout<<root->data<<" ";
*level=max_level;
};
right_view_func(root->right,level,max_level+1);
right_view_func(root->left,level,max_level+1);
}
// main function
void right_view(node *root)
{
int level=0;
right_view_func(root,&level,1);
}
Left View
// utility function
void left_view_func(node *root,int *level,int max_level)
{
if(root==NULL)
return;
if(*level<max_level)
{
cout<<root->data<<" ";
*level=max_level;
}
left_view_func(root->left,level,max_level+1);
left_view_func(root->right,level,max_level+1);
}
// main function
void left_view(node *root)
{
int level=0;
left_view_func(root,&level,1);
}
I hope this tutorial helped you.
Happy Coding!
Comments
Post a Comment
Your Feedback Will Help Us To Improve...