我的打印函数的代码是-
void print(node* root){
cout<<root->data<<" ";
print(root->left);
print(root->right);
return;
}
其中使用的节点结构是:-
struct node
{
int data;
node* left;
node* right;
};
我想不通是什么问题,是不是代码逻辑有问题?
最佳答案
你的递归函数非常接近工作,但它缺少一个基本情况,即当 root
为 nullptr
时,它不会告诉编译器该做什么。当 root
为 nullptr
时添加退出指令将解决问题:
void print(node* root) {
if (!root) return;
... // The remaining code should remain the same
}
注意void
函数底部的return
语句没有特殊用途,应该删除。
关于c++ - 为什么下面的打印树功能不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50107086/