I was solving this question.
When the min
and max
variables are set as global variable, I'm getting the correct output, but when I pass them in the functions it messes up the output.
I can't figure out the reason. Can someone tell me, how are these two code snippets different.
global:
int min = 1,max = 0;
//dfs in which left subtree is travelled before right
void travLeft(Node * root, int i,vector<int> &left)
{
if(root==NULL) return;
if(i<min)
{
min = i;
left.push_back(root->data);
}
travLeft(root->left,i-1,left);
travLeft(root->right,i+1,left);
}
void travRight(Node * root, int i,vector<int> &right)
{
if(root==NULL) return;
if(i>max)
{
max = i;
right.push_back(root->data);
}
travRight(root->right,i+1,right);
travRight(root->left,i-1,right);
}
void topView(Node * root) {
vector<int> left,right;
travLeft(root,0,left);
travRight(root,0,right);
for(int i=left.size()-1;i>=0;i--)
{
cout<<left[i]<<" ";
}
for(int i=0;i<right.size();i++)
{
cout<<right[i]<<" ";
}
}
passing in the function :
//dfs in which left subtree is travelled before right
void travLeft(Node * root,int min, int i,vector<int> &left)
{
if(root==NULL) return;
if(i<min)
{
min = i;
left.push_back(root->data);
}
travLeft(root->left,min,i-1,left);
travLeft(root->right,min,i+1,left);
}
void travRight(Node * root,int max, int i,vector<int> &right)
{
if(root==NULL) return;
if(i>max)
{
max = i;
right.push_back(root->data);
}
travRight(root->right,max,i+1,right);
travRight(root->left,max,i-1,right);
}
void topView(Node * root) {
vector<int> left,right;
travLeft(root,INT_MAX,0,left);
travRight(root,0,0,right);
for(int i=left.size()-1;i>=0;i--)
{
cout<<left[i]<<" ";
}
for(int i=0;i<right.size();i++)
{
cout<<right[i]<<" ";
}
}