c - 二叉搜索树实现的 Inorder 函数不适用于全局结构指针

标签 c binary-search-tree

我写了这段代码-

#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/

相关文章:

c - C中动态确定函数参数的类型?

c - 尝试创建链接列表时出现段错误

c - 二叉搜索树insert方法返回指向节点的指针

java - 我如何比较自定义树集实现中的两个对象?

rotation - 可能的旋转次数。二叉搜索树

c++ - 如何打印祖 parent 是五的倍数的 bst 中的节点?

C 编程 while 循环不要求输入

c - 在 C 中生成排序数组的 n 路交集的高效算法

c - C语言的 war 卡牌游戏

java - 如何在二叉搜索树中找到最小值?