我正在尝试使用二叉搜索树打印给定数组的所有唯一元素。
我在做什么:
- 输入数组中的所有数字。
- 在bst中逐一搜索数组的每个元素,
- if(bst中未找到元素)
- 将其放在那里并打印
- 其他
- 转到下一个元素
- if(bst中未找到元素)
#include<stdlib.h>
#include<stdio.h>
struct node
{
int data;
struct node* left;
struct node* right;
} *root = NULL;
void insert(struct node *n, int value)
{
if (n == NULL)
{
n = (struct node*)malloc(sizeof(struct node));
n->data = value;
n->left = NULL;
n->right = NULL;
printf("%d ", value);
return;
}
if ((n->data) == value)
return;
if ((n->data) > value)
insert(n->left, value);
else
insert(n->right, value);
}
int main()
{
int a[100], i, n;
printf("Enter the number of elements : ");
scanf("%d",&n);
for (i = 0; i < n; i++)
scanf("%d",&a[i]);
printf("After removal of duplicates, the new list is : \n");
for (i = 0; i < n; i++)
insert(root, a[i]);
printf("\n");
return 0;
}
最佳答案
你的代码有一些错误,你的函数插入,应该返回一个结构节点*,否则你将不会构建二叉搜索树。 在您的初始代码中,当您调用 insert 时,您始终使用空节点进行调用。
这就是您应该做的,只需进行最小的更改。
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
struct node
{
int data;
struct node* left;
struct node* right;
} *root = NULL;
struct node* insert(struct node *n, int value)
{
if (n == NULL){
n = (struct node*)malloc(sizeof(struct node));
n->data = value;
n->left = NULL;
n->right = NULL;
printf("inserted %d\n", value);
return n;
}else{
if( value == n->data){
printf("Duplicated Value %d\n", value);
return n;
}
if ( (n->data) > value ){
n->left = insert(n->left, value);
}else{
n->right = insert(n->right, value);
}
return n;
}
}
int main()
{
int a[100], i, n;
printf("Enter the number of elements : ");
scanf("%d",&n);
for (i = 0; i < n; i++)
scanf("%d",&a[i]);
printf("After removal of duplicates, the new list is : \n");
for (i = 0; i < n; i++)
root = insert(root, a[i]);
printf("\n");
return 0;
}
顺便说一下,this应该有帮助,这是一个测试 example 。 ;)
您应该在知道大小之后创建数组,否则您可能会分配太多内存。当然,您应该让用户能够创建包含超过 100 个元素的二叉树
int i, n;
printf("Enter the number of elements : ");
scanf("%d",&n);
int a[n];
关于c - 打印数组的所有唯一元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30529469/