简体   繁体   English

用指针打印二进制搜索树C ++的奇怪方法

[英]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. 该函数正在将指针传递到尚未在'cout'行中的节点,它试图访问节点结构中的键值而不先取消引用它。 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; cout<<(*t).key<<endl;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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