中序遍历——C语言向Int数组添加节点数据

Inorder Traversal - Add Node Data to Int Array in C Langauge

我正在用C语言实现中序遍历算法,下面是我的代码。我的任务是将每个节点的数据添加到 nodeDataList 中。但是,nodeDataList 正在存储奇怪的数据,

void inorder(Node* N, int* nodeDataList, int index){
   if(N != NULL){
       inorder(N->left, nodeDataList, index);
       printf("%d: %d ", index, N->data);
       nodeDataList[index++] = N->data;
       inorder(N->right, nodeDataList, index);
   }
}

下面是main函数中的设置,

struct Node root = {27, NULL, NULL};
struct Node root_left = {26, NULL, NULL};
struct Node root_right = {39, NULL, NULL};
struct Node root_right_right = {48, NULL, NULL};
struct Node root_right_left = {40, NULL, NULL};
struct Node *N;
struct Node *N_left;
struct Node *N_right;
struct Node *N_right_right;
struct Node *N_right_left;
N = &root;
N_left = &root_left;
N_right = &root_right;
N_right_right = &root_right_right;
N_right_left = &root_right_left;

N_right->right = N_right_right;
N_right->left = N_right_left;

N->left = N_left;
N->right = N_right;
int result = 5;

int nodeDataList[result];
int index = 0;

inorder(N, nodeDataList, index);
printf("\n");

printf("%d\n", nodeDataList[0]);
printf("%d\n", nodeDataList[1]);
printf("%d\n", nodeDataList[2]);
printf("%d\n", nodeDataList[3]);
printf("%d\n", nodeDataList[4]);

当运行代码时,我得到以下数据,

0: 26 0: 27 1: 40 1: 39 2: 48 
27
39
48
-1427448988
-1086203488

我不确定 -1427448988 和 -1086203488 是什么。我已经正确创建了 inorder,但 int 数组在索引 3 和 4 处生成了不正确的数据。

您在传递最后一个参数时遇到问题 index。按值传递它不会在后续调用之间保留其值。

试试这个:

#include <stdio.h>

struct Node
{
    int data;
    struct Node *left;
    struct Node *right;
};
typedef struct Node Node;

void inorder(Node* N, int* nodeDataList, int *index){
   if(N != NULL){
       inorder(N->left, nodeDataList, index);
       printf("%d: %d ", *index, N->data);
       nodeDataList[(*index)++] = N->data;
       inorder(N->right, nodeDataList, index);
   }
}



int main(void){
    struct Node root = {27, NULL, NULL};
    struct Node root_left = {26, NULL, NULL};
    struct Node root_right = {39, NULL, NULL};
    struct Node root_right_right = {48, NULL, NULL};
    struct Node root_right_left = {40, NULL, NULL};
    struct Node *N;
    struct Node *N_left;
    struct Node *N_right;
    struct Node *N_right_right;
    struct Node *N_right_left;
    N = &root;
    N_left = &root_left;
    N_right = &root_right;
    N_right_right = &root_right_right;
    N_right_left = &root_right_left;

    N_right->right = N_right_right;
    N_right->left = N_right_left;

    N->left = N_left;
    N->right = N_right;
    int result = 5;

    int nodeDataList[result];
    int index = 0;

    inorder(N, nodeDataList, &index);
    printf("\n");

    printf("%d\n", nodeDataList[0]);
    printf("%d\n", nodeDataList[1]);
    printf("%d\n", nodeDataList[2]);
    printf("%d\n", nodeDataList[3]);
    printf("%d\n", nodeDataList[4]);
}
``