树排序不排序我的数组

问题描述 投票:1回答:1

我必须在C中实现树排序,但尽管尽可能遵循经典算法,但我无法使其工作。这是我的代码:

searchTreeSort.h:

#ifndef UTILS_H
#define UTILS_H

#include "utils.h"

#endif


//Déclaration d'une structure représentant un noeud d'arbre
struct _node;
typedef struct _node NODE;

typedef NODE *TREE;

TREE newNode(int item);
TREE insert(TREE node, int key);
void storeInOrder(TREE root, ARRAY t, int i);
void freeAllNodes(TREE root);
void displayNodes(TREE root);
void searchTreeSort(ARRAY t, int max);

searchTreeSort.c:

#include "searchTreeSort.h"

struct _node{
    int value;
    TREE left;
    TREE right;
};

TREE newNode(int item){
    TREE t = malloc(sizeof(NODE));
    t->value = item;
    t->left = NULL; 
    t->right = NULL;
    return t;
}

TREE insert(TREE root, int item){
    if(root == NULL)
        return newNode(item);

    if(item < root->value){
        root->left = insert(root->left, item);
    }
    else if(item > root->value){
        root->right = insert(root->right, item);
    }

    return root;
}

void storeInOrder(TREE root, ARRAY t, int i){
    if(root != NULL){
        storeInOrder(root->left, t, i);
        t[i++] = root->value;
        storeInOrder(root->right, t, i);
    }
}

void freeAllNodes(TREE root){
    if(root != NULL){
        freeAllNodes(root->left);
        freeAllNodes(root->right);
        free(root);
    }
}

void displayNodes(TREE root){
    if(root != NULL){
        displayNodes(root->left);
        displayNodes(root->right);
        printf("%d\n", root->value);
    }
}

void searchTreeSort(ARRAY t, int max){
    TREE root = NULL;
    root = insert(root, t[0]);
    for(int i = 1; i < max; i++){
        insert(root, t[i]);
    }

    int i = 0;
    storeInOrder(root, t, i);
    //displayNodes(root);
    freeAllNodes(root);
}

在utils.h中,我有以下typedef:typedef int ARRAY [MAX];和所述MAX值的定义。

在main中,我用随机值填充我的ARRAY t,然后像这样调用我的函数:searchTreeSort(t,max);

除了当我在排序之前和之后显示我的ARRAY时,绝对没有任何改变:元素保持相同的顺序。

函数displayAllNodes向我展示了树是正确创建的,这是将元素以正确的顺序存储在数组中的最后一步,似乎出错了。

我已经在线程上看到了一些像这样的解决方案:C binary tree sort - extending it但是我必须使用typedef int ARRAY [MAX];并且在使用它时不知道如何实现那些更多指针密集型解决方案。

你能帮我找出问题的来源吗?提前致谢。

c arrays sorting
1个回答
1
投票

好吧它应该出错了。您传递的值i是按值传递的。你在一个函数中增加它。但这无论如何都不会反映对同一函数的其他调用。您正在覆盖已写入的值。那么解决方案是什么?很简单。传递变量的地址。

void storeInOrder(TREE root, ARRAY t, int* i){
    if(root != NULL){
        storeInOrder(root->left, t, i);
        t[(*i)++] = root->value;
        storeInOrder(root->right, t,i);
    }
}

你这么称呼它

storeInOrder(root, t, &i);
                     ^^^ passing the address.

在头文件中更改声明

void storeInOrder(TREE root, ARRAY t, int* i);
© www.soinside.com 2019 - 2024. All rights reserved.