user1893354 user1893354 - 23 days ago 6
C++ Question

Strange way of printing Binary Search Tree C++ with pointers

I was going through a lecture and it showed some code that prints out a binary search tree recursively like this

void printTree(node *t){
if(t!=NULL){
printTree(t->left);
cout<<t->key<<endl;
printTree(t->right);
}
}


I understand what it is doing but I don't understand the pointers. The function is passing a pointer to a node yet in the 'cout' line, it is trying to access the key value in the node struct without dereferencing it first. What I mean is, shouldn't it be something like

cout<<(*t)->key<<endl;


instead?

Answer

Actually, -> is a dereferencing operator. You can make a choice:

cout<<t->key<<endl; or cout<<(*t).key<<endl;