编程知识 cdmana.com

Suppression de l'arbre de tri binaire infructueuse

#include<stdio.h>#include<stdlib.h>typedef struct Node {    int data;    struct Node* left;    struct Node* right;}Node;typedef struct  {    Node* root;}Tree;void addnode(Tree* tree, int data) {    Node* node = (Node*)malloc(sizeof(Node));    node->data = data;    node->left = NULL;    node->right = NULL;    if (tree->root == NULL) {        tree->root = node;    }    else {        Node* temp = (Node*)malloc(sizeof(Node));//Stocker le contenu actuel du noeud racine        temp = tree->root;        while (temp != NULL) {            if (temp->data > data) {                if (temp->left == NULL) {                    temp->left = node;                    return;                }                else {                    temp = temp->left;                }            }            else {                if (temp->data < data) {                    if (temp->right == NULL) {                        temp->right = node;                        return;                    }                    else {                        temp = temp->right;                    }                }            }        }    }}Node* findmin(Node* node) {    if (node == NULL)        return NULL;    while (node->left != NULL)        node = node->left;    return node;}bool denode(Node* node, int data) {    Node* temp = (Node*)malloc(sizeof(Node));    temp = node;    while (temp->data != data) {        if (temp->data > data) {            temp = temp->left;        }        else {            temp = temp->right;        }    }if (temp->left == NULL && temp->right ==NULL) {        temp = NULL;    }    else if (temp->left != NULL && temp->right == NULL) {                temp = temp->left;    }    else if (temp->right != NULL && temp->left == NULL) {        temp = temp->right;    }    else {        Node* pre = findmin(temp->right);        temp->data = pre->data;        free(pre);    }    return true;}void firorder(Node* node) {    if (node != NULL) {        printf("%d\n", node->data);        firorder(node->left);        firorder(node->right);    }}int main() {    int arry[7] = { 6,3,8,2,5,1,7 };    Tree tree;    tree.root = NULL;    for (int i = 0; i < 7; i++) {        addnode(&tree, arry[i]);    }    firorder(tree.root);    printf("--------\n");    addnode(&tree, 4);    firorder(tree.root);    printf("--------\n");    denode(tree.root, 7);    firorder(tree.root);}
Supprimer ne peut pas supprimer sans noeud parent ou un seul noeud parent , Erreur signalée lors de la suppression de deux noeuds parents

img


img

532158F632154854215572662307``



Voir la réponse1:

Lors de la suppression, vous devez vérifier si le pointeur est vide




Voir la réponse2:

版权声明
本文为[Questions et réponses du rseoc]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/11/20211125162307550M.html

Scroll to Top