plz help me how to do that
Right view of a tree
You can do this by simple DFS traversal. The last node of each horizontal level of tree will form the right side view.
The function in your code must be something like this. Follow the comments.
//Global variables:
vector< int >result;//To strore the result or the elements of right size view
int maxlevel=-1;
void helper(TreeNode* root,int level)
{
//Base Case--
if(root==NULL)
return;
//Work to be done:
//The first visited node of each particular level is pushed into the result vector.
//Since in traversal order right node comes first..so the first visited node of each particular level will be the rightmost node
if(level>maxlevel)
{
maxlevel=level;
result.push_back(root->val);
}
//Trversal order--
helper(root->right,level+1);//First Traverse Right since this will lead to the rightmost node first
helper(root->left,level+1);
return;
}
vector<int> rightSideView(TreeNode* root)
{
helper(root,0);
return result;
}
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.