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]<<" ";
}
}
The global variable is global. The changes to the value will retain among all calls of travLeft
and travRight
.
On the other hand, the argument is local to the function. The new value of min
and max
are passed to the next level of recursion, but the update of min
in the first recursion
travLeft(root->left,min,i-1,left);
will not passed to the second recursion
travLeft(root->right,min,i+1,left);
Because the same value of min
, which is updated (or not updated and come from the previous level) at this level, is passed for the two calls.
The same thing will also happen with max
and travRight
.
This is the difference.