【发布时间】:2021-03-09 14:10:48
【问题描述】:
我试图在 C 中创建一个 BST。我只是添加了一些基本功能。但是,我似乎遇到了添加节点或按顺序遍历的问题 - 不知何故创建了一个无限循环。请提供反馈,因为我正在努力改进。谢谢!
#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;
}
【问题讨论】:
-
您的
insert缺少案例处理x == root->data。并不是说它是 问题。 -
你为什么要用 C++ 标记一个关于 C 的问题?
-
您的
inorder中不需要while循环。仅递归就足以完成完整遍历。这就是无限循环的所在——root永远不会在那里更新。将while替换为if。 -
@EugeneSh.Thanks !!
标签: c algorithm data-structures binary-search-tree