For example in this code:
node* find(node *cur, int id){
node* p;
if (cur->id==id) {printf("\n%d found at %p\n", id, cur); return cur;}
else{
if (cur->left!=NULL) p=find(cur->left, id);
if ((p==NULL) && (cur->right!=NULL)) p=find(cur->right, id);
}
}
The aim of this function is to return the address of the node which have the id equal to the provided id.
In main I have:
while (1){
fscanf(fi, "%d", &id);
if (id==-2) break;
fscanf(fi, "%d %d", &left, &right);
cur=find(root, id);
printf("%p\n", cur);
if (cur==NULL) continue;
printf("%d\n\n", cur->id);
if (left!=-1) cur->left=makeNode(left);
if (right!=-1) cur->right=makeNode(right);
}
Notice the part
cur=find(root, id);
printf("%p\n", cur);
if (cur==NULL) continue;
printf("%d\n\n", cur->id);
If I change if ((p==NULL) && (cur->right!=NULL)) p=find(cur->right, id);
to if ((cur->right!=NULL) && (p==NULL)) p=find(cur->right, id);
I'll get the wrong answer, i.e.
With if ((p==NULL) && (cur->right!=NULL)) p=find(cur->right, id);
, I got:
2 found at 0x56552970dcd0
0x56552970dcd0
2
4 found at 0x56552970dcf0
0x56552970dcf0
4
But with if ((cur->right!=NULL) && (p==NULL)) p=find(cur->right, id);
, I got
2 found at 0x564024e5ccd0
0x564024e5ccf0
4
4 found at 0x564024e5ccf0
0x564024e5ccf0
4
Can anyone explain to me why this happens? Sorry for the long post and my bad English. Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire