BST节点删除功能在递归调用失败

时间:2016-08-16 23:22:30

标签: c algorithm data-structures binary-tree binary-search-tree

void search(struct node **root, struct node **cursor,
            struct node **parent, int data, int *found) {
    struct node *iterator = *root;

    *cursor = NULL, *parent = NULL;
    *found = FALSE;

    while (iterator != NULL) {
        if (data == iterator->data) {
            *found = TRUE;
            *cursor = iterator;
            break;
        } else
        if (data <= iterator->data) {
            *parent = iterator;
            iterator = iterator->left;
        } else {
            *parent = iterator;
            iterator = iterator->right;
        }
    }
}

void delete(struct node **root, int data) {
    int found;
    struct node *cursor, *parent;

    if (*root == NULL) {
        printf("ERROR! Binary Search Tree Empty!\n");
        exit(0);
    }
    search(root, &cursor, &parent, data, &found);
    if (found == FALSE) {
        printf("ERROR! Element not found in Binary Tree!\n");
        exit(0);
    }
    //  If the Node has No Children
    if (cursor->left == NULL && cursor->right == NULL) {
        if (parent->left == cursor) {
            parent->left = NULL;
        } else {
            parent->right = NULL;
        }
        free(cursor);
    }
    if (cursor->left == NULL && cursor->right != NULL) {
        if (parent->left == cursor) {
            parent->left = cursor->right;
        } else {
            parent->right = cursor->right;
        }
        free(cursor);
    }
    if (cursor->left != NULL && cursor->right == NULL) {
        if (parent->left == cursor) {
            parent->left = cursor->left;
        } else {
            parent->right = cursor->left;
        }
        free(cursor);
    }
    // If node has two children
    if (cursor->left != NULL && cursor->right != NULL) {
        struct node *iterator = cursor;
        iterator = iterator->right;
        while (iterator->left != NULL) {
            iterator = iterator->left;
        }
        cursor->data = iterator->data;
        printf("\n%i\n", iterator->data);
        delete(&iterator, iterator->data);
    }
}

我正在尝试实现二进制搜索树删除功能。我已经测试了许多BST,但是当我删除有两个孩子的节点时它失败了。它在递归调用时失败。它给出分段错误11 。我该怎么办?

1 个答案:

答案 0 :(得分:0)

delete功能的问题是每次free(cursor);后都不会返回。而是继续测试下一个案例,解除引用刚刚释放的cursor。问题主要是cursor有1个孩子或没有孩子。