c - 打印数组的所有唯一元素

标签 c binary-search-tree

我正在尝试使用二叉搜索树打印给定数组的所有唯一元素。

我在做什么:

  1. 输入数组中的所有数字。
  2. 在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/

相关文章:

C++从树中检索对象

c - 具有灵活数组成员的结构数组如何表现?

c - 这个混淆的 C 行如何打印 "EMIL"?

c - 此函数如何仅使用按位运算符对 3 个整数求和?

c++ - 使用 C++ 从排序的 std::list<float> 构建最小高度 BST

java - 通过递归方法跟踪激活记录

c - 符号位在 32 位机器中是如何表示的

c++ - OpenMP 更新结构的最快方法

c - 将文本文件中的单词插入到 C 树中

java - 二叉搜索树 tree.root 返回 null