调试C中的二叉搜索树
我试图用C语言创建一个BST。我只是添加了一些基本的功能。然而,我似乎遇到了一个问题,要么添加一个节点,要么使用顺序遍历——不知何故创建了一个无限循环。请提供反馈,因为我正在努力改进。谢谢调试C中的二叉搜索树,c,algorithm,data-structures,binary-search-tree,C,Algorithm,Data Structures,Binary Search Tree,我试图用C语言创建一个BST。我只是添加了一些基本的功能。然而,我似乎遇到了一个问题,要么添加一个节点,要么使用顺序遍历——不知何故创建了一个无限循环。请提供反馈,因为我正在努力改进。谢谢 #include <stdio.h> #include <stdlib.h> //node structure struct node{ int data; struct node* left; struct node* right; }typedef node; //c
#include <stdio.h>
#include <stdlib.h>
//node structure
struct node{
int data;
struct node* left;
struct node* right;
}typedef node;
//create node
node * createLeaf(int x){
node * temp = (node*)malloc(sizeof(node));
temp->data = x;
temp->left = NULL;
temp->right = NULL;
return temp;
}
//insert node
node *insert(node *root,int x){
if(root == NULL){
root = createLeaf(x);
return root;
}
else{
if(x > root->data){
root->right = insert(root->right,x);
}
else if(x < root->data){
root->left = insert(root->left,x);
}
}
return root;
}
//in-order traversal
void inorder(node * root){
while(root!=NULL){
inorder(root->left);
printf("%d\n",root->data);
inorder(root->right);
}
}
int main()
{
node * root = NULL;
root = insert(root,5);
insert(root,8);
insert(root,1);
inorder(root);
printf("Hello World");
return 0;
}
#包括
#包括
//节点结构
结构节点{
int数据;
结构节点*左;
结构节点*右;
}typedef节点;
//创建节点
节点*createLeaf(int x){
node*temp=(node*)malloc(sizeof(node));
温度->数据=x;
temp->left=NULL;
temp->right=NULL;
返回温度;
}
//插入节点
节点*插入(节点*根,int x){
if(root==NULL){
root=createLeaf(x);
返回根;
}
否则{
如果(x>根->数据){
根->右=插入(根->右,x);
}
else if(xdata){
根->左=插入(根->左,x);
}
}
返回根;
}
//顺序遍历
无效索引(节点*根){
while(root!=NULL){
顺序(根->左);
printf(“%d\n”,根->数据);
顺序(根->右);
}
}
int main()
{
node*root=NULL;
根=插入(根,5);
插入(根,8);
插入(根,1);
顺序(根);
printf(“你好世界”);
返回0;
}
@Eugene建议用if替换while可以解决问题
或者,您可以在while循环的末尾添加一个中断,这也应该可以解决您的问题。
但是我建议只使用递归或迭代。您的
insert
缺少大小写处理x==root->data
。这不是问题。为什么你用C++来标注关于C的问题?你不需要<代码>而<代码> > <代码> > < < />代码>。仅递归就足以进行完整遍历。这就是无限循环所在的位置-根
永远不会在那里更新。将while
替换为if
@EugeneSh。谢谢!!