Home > Blockchain >  An error occurs during the implementation of the linked list tree
An error occurs during the implementation of the linked list tree

Time:05-20

enter code here

#include <stdio.h>
#include <stdlib.h>
typedef struct _node {
   int data;
   struct _node* rightChild;
   struct _node* leftChild;
}Node;


Node* create(int data) { // create node function
   Node* node = (Node*)malloc(sizeof(node));
   node->rightChild = NULL;
   node->leftChild = NULL; 
   node->data = data;
   return node;
}

void Inorder(Node* ptr) { // travel
   if (ptr) 
   {
       printf("%c ", ptr->data);
       Inorder(ptr->leftChild);
       Inorder(ptr->rightChild); 
   }
 }
int main(void)
{
   Node* node[300];
   for (int i = 1; i < 300; i  ) {
       if (i == 1) {
           node[i] = create(i);
       }
       else {
           if (i % 2 == 0) {
               node[i / 2]->leftChild = create(i);
           }
           else {
               node[i / 2]->rightChild = create(i);
           }
       }
   }
    Inorder(node[10]);
}

I would like to implement a binary tree using a Node* array, rather than taking variables input one by one. But I keep getting errors in that area. Thanks for the advice.Which part do I need to modify to make that part implemented through a for statement? As far as I understand, both the left and right parts of the node array have passed values, so why am I getting an error?

CodePudding user response:

The only node[i] you assign to is node[1]. All other nodes are linked via the the leftChild or rightChild fields.

You could fix this by doing, for example:

node[i] = create(i);
node[i / 2]->leftChild = node[i];

but I this is a bit roundabout, because you now have the same data – the handle to a node — in two different places.

My guess is that what you really want is a plain array of node structures, which are then linked via pointers into the array:

Node node[300] = {{0}};

node[1].data = 1;

for (int i = 2; i < 300; i  ) {
    node[i].data = i;        

    if (i % 2 == 0) {
        node[i / 2].leftChild = &node[i];
    } else {
        node[i / 2].rightChild = &node[i];
    }
}

This creates a flat array of nodes, where the nodes are linked like a binary tree. For example, node[1].leftChild is a pointer to node[2]. You can use regular tree functions by passing &node[1] as head:

Inorder(&node[1]);

(What you call Inorder is really a pre-order traversal.)

The advantage is that you don't need to create and allocate anything. When main ends, the whole tree is gone without needing to free. (It also gets rid of a bug in create, where you allocate space for a pointer only, not for a node; it should be node = malloc(sizeof(*node));.)

Perhaps that's not what you want, but the bug in your code comes from accessing node[2] when it hasn't been set.

  • Related