//set equal=0 before calling trace function.
int equal=0;
void trace(node
*r,int item)
{
if(equal==1)
return;
if(r->data==item)
equal=1;
if(r!=NULL)
{
trace(r->left,item);
trace(r->right,item);
if(equal==1)
cout<<" "<<r->data;
}
}
it wont print the trace... it will just say whether the node is present or not!!
ReplyDeletecorrect me if i m wrong
By trace I meant print the path from root node to the given node.
ReplyDelete10
20 30
40 50 60 70
80 90
In above example to path to reach 90 from root (10) is:
90 -> 40 -> 20 -> 10
void trace(node *r,int path[],int pathLen,int item)
ReplyDelete{
if(root ==NULL)
return;
path[pathLen] = root->dara;
pathLen++;
if(root->left == NULL && root->right == NULL)
printArray(path,pathLen)
else
{
trace(r->left,path,pathLen,item);
trace(r->right,item,path,pathLen,item);
}
}
void printArray(int path[],int pathLen)
{
for(int i =0;i<pathLen;i++)
cout <<path[i];
}
sorry above algo for all possible path from root to leaf . if you want to trace the path for any specific item you will add one extra check
ReplyDeleteif( root-data == item)
{
printArray(path,pathLen);
}