c - 中序遍历是以错误的顺序打印

标签 c string binary-search-tree

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<string.h>
struct node{
 char *name;
 struct node *lchild;
 struct node *rchild;
};
void find(char *str,struct node **root,struct node **loc,struct node **par)
{
struct node *ptr,*ptrsave;
*loc=NULL;
*par=NULL;
if(*root==NULL)
{
   return;
}
if(!strcmp((*root)->name,str))
{
     *loc=*root;
     return;
}
ptrsave=NULL;
ptr=*root;
while(ptr!=NULL)
{
   if(!strcmp(ptr->name,str)) break;
   ptrsave=ptr;
   if(strcmp(ptr->name,str)>0)
      ptr=ptr->lchild;
   else
      ptr=ptr->rchild;
}
*loc=ptr;
*par=ptrsave;
}
void insert(struct node **p,char *str)
{
struct node *location,*parent,*temp;
find(str,&(*p),&location,&parent);
if(location!=NULL)
{
       printf("Element already exists\n");
       return;
}
temp=(struct node *)malloc(sizeof(struct node));
temp->name=strdup(str);
temp->lchild=NULL;
temp->rchild=NULL;
if(parent==NULL)
{
        *p=temp;
        return;
}
else
{
     if(strcmp(parent->name,str)>0)
        parent->lchild=temp;
     else
        parent->rchild=temp;
}
}


void inorder(struct node *root)
{
if(root!=NULL)
{
   preorder(root->lchild);
   printf("[%30s]\n",root->name);
   preorder(root->rchild);
}
}
int main()
{
struct node *root=NULL;
insert(&root,"Crocin");
insert(&root,"Acetyl");
insert(&root,"Colchichine");
insert(&root,"Diclofenac_50mg");
insert(&root,"Diclofenac_25mg");
insert(&root,"Morphine Sulphate");
insert(&root,"Fentanyl");
insert(&root,"Dolo");
insert(&root,"Ibuprofen");
insert(&root,"Tramadol");
insert(&root,"Paracetamol");
inorder(root);
getchar();
return 0;
}

这是我用来在二叉搜索树中创建和插入节点的代码。之后我创建了递归中序函数。但这并没有给出正确的输出。我找不到造成差异的错误。有人可以建议我哪里出错了吗?

最佳答案

改变

void inorder(struct node *root)
{
if(root!=NULL)
{
   preorder(root->lchild);
   printf("[%30s]\n",root->name);
   preorder(root->rchild);
}

void inorder(struct node *root)
{
if(root!=NULL)
{
   inorder(root->lchild);
   printf("[%30s]\n",root->name);
   inorder(root->rchild);
}

您正在使用另一个函数(预购)(未在您的代码中列出)

关于c - 中序遍历是以错误的顺序打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19829394/

相关文章:

c - PostQuitMessage() 是否进入 WM_DESTROY 或 WM_CLOSE?

在预定义结构上创建动态 vector

c - sizeof 在添加和计算时如何针对不同的数据类型工作?

c - 多线程 Web 服务器的线程池

java - 将大字符串分成小字符串

java - 从字符串获取资源

来自 "Pro Coder"示例的 Python 二叉搜索树

c++ - 在 BST 中搜索节点时出现段错误

Java:如何从字符串中抓取每行

java - 将两个独立的 ADT 合并为一个