1
struct node {
    int data;
    struct node* left;
    struct node* right;
};

挿入するノードを作成する関数:

struct node* create_node(int val) {

 // Allocate space for the node, set the fields.
 struct node* temp;
 temp = (struct node*)malloc(sizeof(struct node));
 temp->data = val;
 temp->left = NULL;
 temp->right = NULL;

 return temp; // Return a pointer to the created node.
}

私の挿入ノード機能:

struct node* insert(struct node *root, struct node *element) {

 if (root == NULL)
   return element;
 else {

   // element should be inserted to the right.
   if (element->data > root->data) {

     // There is a right subtree to insert the node.
     if (root->right != NULL)
       root->right = insert(root->right, element);

     // Place the node directly to the right of root.
     else
       root->right = element;
   }

   // element should be inserted to the left.
   else {

     // There is a left subtree to insert the node.
     if (root->left != NULL)
       root->left = insert(root->left, element);

     // Place the node directly to the left of root.
     else
       root->left = element;
   }

   // Return the root pointer of the updated tree.
   return root;
 }
}

ノードをツリーに挿入している私のメイン:

    scanf("%d", &numCases);

    for(i=0; i<numCases;i++){

        scanf("%d", &numNodes);

        for(j=0; j < numNodes; j++){
            scanf("%d", &val);
            temp_node = create_node(val);
            my_root = insert(my_root, temp_node);
        }
// calling the function to free the tree after all nodes have been inserted
postOrderFree(my_root);

今、私の計画では、ポスト オーダー トラバース メソッドを使用して各ノードを解放することでしたが、ポスト オーダー機能を使用しようとすると、正しく動作しないようです。ノードはまったく解放されず、私が与えたすべてのケースで、必然的にクラッシュするまで、前のツリーにノードを追加し続けます。

これは、私が使用しようとしている Post order traverse 関数です。

void postOrderFree(struct node* root){
    if(root != NULL) {
        postOrderFree(root->left);
        postOrderFree(root->right);
        free(root->data);
    }
}

スタイルを含め、冗長性がある場合は、あらゆる助けをいただければ幸いです。

4

2 に答える 2

2

データではなくノードにメモリを割り当てたので、ノード データを解放するのではなく、ノード自体を解放する必要があります。

void postOrderFree(struct node* root){
    if(root != NULL) {
        postOrderFree( root->left );
        postOrderFree( root->right );
        free( root );
    }
}
于 2013-10-24T19:42:15.360 に答える
2

あなたの postOrderFree() 関数は間違ったものを解放します..

そのはず

 free(root);

それ以外の

  free(root->data);

バイナリ ツリーを解放した後、ルート ノードも NULL に戻す必要があります。そうしないと、ダングリング ポインターになります。つまり、これを行う必要があります。

 postOrderFree(my_root);
 my_root = NULL;
于 2013-10-24T19:44:51.307 に答える