Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Viết chương trình xóa cây (Delete a Tree) trong C


Để xóa cây, duyệt từng nút và xóa lần lượt. Cách tốt nhất: duyệt từ dưới lên (postorder) để xóa nút con trước, rồi nút cha, tránh rò rỉ bộ nhớ.

Duyệt postorder của cây ví dụ: 2-6-4-12-17-15

Postorder: nút trái -> nút phải -> gốc.

Viết chương trình xóa cây (Delete a Tree) trong C

Ví dụ

#include <stdio.h>
#include <stdlib.h>

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

struct node* addnode(int data) {
    struct node* node = (struct node*) malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return(node);
}

void nodedel(struct node* node) {
    if (node == NULL) return;
    nodedel(node->left);
    nodedel(node->right);
    printf("\n Node deleted, value is %d", node->data);
    free(node);
}

int main() {
    struct node *root = addnode(9);
    root->left = addnode(4);
    root->right = addnode(15);
    root->left->left = addnode(2);
    root->left->right = addnode(6);
    root->right->left = addnode(12);
    root->right->right = addnode(17);
    nodedel(root);
    root = NULL;
    printf("\n Tree deleted ");
    return 0;
}

Kết quả

Node deleted, value is 4
Node deleted, value is 12
Node deleted, value is 17
Node deleted, value is 15
Node deleted, value is 9
Tree deleted