我写了这段代码-
#include<stdio.h>
#include<stdlib.h>
struct nd{
int data;
struct nd *left;
struct nd *right;
};
struct nd *root = NULL;
void create_tree(){
int key;
printf("Enter a value that you want to insert-\n");
scanf("%d", &key);
insert(key);
}
void insert(int key){
struct nd *temp, *follow, *p;
temp=(struct nd*)malloc(sizeof(struct nd));
//If malloc doesn't allocate space and returns NULL then print the reason
if(temp == NULL){
printf("Memory overflow!");
return;
}
temp->data = key;
temp->left = temp->right = NULL;
if(root == NULL){
root=temp;
}else{
p=root;
follow=NULL;
while(p!=NULL){
follow=p;
if(temp->data<p->data){
p=p->left;
}else{
p=p->right;
}
}
if(temp->data<follow->data){
follow->left=temp;
}else{
follow->right=temp;
}
}
printf("\nInsertion Successful!\n");
}
void inorder(){
if(root!=NULL){
inorder(root->left);
printf("%d",root->data);
inorder(root->right);
}
}
void main(){
create_tree();
create_tree();
create_tree();
create_tree();
inorder();
}
该代码不输出中序遍历数据。但是如果我将 main() 函数中的 inorder() 函数调用更改为此 -
inorder(root);
并给函数一个这样的参数-
void inorder(struct nd *root){
if(root!=NULL){
inorder(root->left);
printf("%d",root->data);
inorder(root->right);
}
}
突然,它给出了预期的输出,即它显示了创建的树的中序遍历数据。但是由于根变量被定义为全局变量,我的问题是为什么我们必须将该根变量传递给中序函数?由于 root 是一个全局变量,那么所有函数都可以访问该变量,对吧?所以我无法理解为什么会发生这种情况。
最佳答案
中序函数签名不匹配 在定义中它是 () 但在函数内部您使用参数调用它
签名:void inorder() 调用:inorder(root->left);
关于c - 二叉搜索树实现的 Inorder 函数不适用于全局结构指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47370402/