简体   繁体   中英

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?

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

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

但是绝对不是“(* t)-> key”-这将是双重deref,如果不是崩溃,可能是编译错误。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM