La eliminación de todo el árbol binario de búsqueda a la vez

votos
-1

He estado tratando de implementar la función de borrado BST, pero no sé por qué no está funcionando, creo que es lógicamente correcto. Cualquier organismo puede por favor dígame, ¿por qué estoy recibiendo el error de tiempo de ejecución y cómo debo corregirlo.

  #include <iostream>
  using namespace std;

class node{
public:
int data;
node *right;
node *left;
node(){
    data=0;
    right=NULL;
    left=NULL;
      }
};

class tree{
node *head;
int maxheight;
     public:
tree(){head=0;maxheight=-1;}
bool deletenode(int key,node* root);
int get_height(){return maxheight;}
void insert(int key);
void pre_display(node* root);
     void delete_tree(node *root);
     node* get_head(){return head;}
         };

void tree::insert(int key){
     node *current=head;
    node *newnode=new node;

    if(newnode==NULL)
    throw(key);

    newnode->data=key;
    int height=0;

if(head==0){
head=newnode;
     }
else
{
    while(1){
    if(current->right==NULL && current->data < newnode->data)
    {
        current->right=newnode;
        height++;
        break;
    }
    else if(current->left==NULL && current->data > newnode->data)
    {
        current->left=newnode;
        height++;
        break;
    }
    else if(current->right!=NULL && current->data < newnode->data)
    {
         current=current->right;
         height++;
   }
    else if(current->left!=NULL && current->data > newnode->data)
    {
               current=current->left;
          height++;
    }
         }
 }
 if(height>maxheight)
 maxheight=height;
 }

 void tree::pre_display(node *root){
 if(root!=NULL)
 {
 cout<<root->data<< ;
 pre_display(root->left);
 pre_display(root->right);
 }
 }

 void tree::delete_tree(node *root){
  if(root!=NULL)
 {
 delete_tree(root->left);
 delete_tree(root->right);
 delete(root);
 if(root->left!=NULL)
 root->left=NULL;
 if(root->right!=NULL)
 root->right=NULL;
 root=NULL;
 }
 }

int main(){
tree BST;
int arr[9]={17,9,23,5,11,21,27,20,22},i=0;

for(i=0;i<9;i++)
BST.insert(arr[i]);

BST.pre_display(BST.get_head());
cout<<endl;
BST.delete_tree(BST.get_head());
BST.pre_display(BST.get_head());
cout<<endl;

system(pause);
return 0;
}

Todas las demás funciones están trabajando correctamente, sólo tiene que comprobar la delete_treefunción, se proporciona otro código para dar la idea de la estructura de mi BST.

Publicado el 09/11/2011 a las 09:22
fuente por usuario
En otros idiomas...                            


7 respuestas

votos
0

No se debe leer desde la raíz después de eliminarlo. Mover la delete(root)línea hacia abajo.

Respondida el 09/11/2011 a las 09:26
fuente por usuario

votos
3

En su delete_tree

void tree::delete_tree(node *root){
    if(root!=NULL)
    {
        delete_tree(root->left);
        delete_tree(root->right);
        delete(root);
        if(root->left!=NULL)
            root->left=NULL;
        if(root->right!=NULL)
            root->right=NULL;
        root=NULL;
    }
}

que está accediendo a raíz variable después de haber borrado

También se llama

    BST.delete_tree(BST.get_head());
BST.pre_display(BST.get_head());

pre_display después de eliminar árbol. delete_tree después de eliminar el árbol también debe establecer el BST.head a NULL

También una crítica. BST es de tipo árbol. Ya tiene una variable miembro de cabeza que indica el nodo raíz. Así delete_tree / pre_display no necesita ningún parámetro en absoluto.

Respondida el 09/11/2011 a las 09:27
fuente por usuario

votos
1

El problema está aquí:

 delete_tree(root->left);
 delete_tree(root->right);
 delete(root);
 if(root->left!=NULL)
 root->left=NULL;
 if(root->right!=NULL)
 root->right=NULL;
 root=NULL;

Usted está tratando de asignar NULL a un miembro de la raíz:

root->left=NULL;

que ya ha sido eliminada. No hay necesidad de hacer eso ya que ya está liberando la memoria dedelete_tree(root->left);

Respondida el 09/11/2011 a las 09:28
fuente por usuario

votos
0

Recursiva eliminar sub-árbol izquierdo y derecho y su árbol se borrará tan simple como:

void delete(node *root){
  if(root->left==NULL && root->right==NULL)  //leaf node, delete it!!
    free(root);
  delete(root->left);
  delete(root->right);
 }
Respondida el 15/07/2014 a las 18:12
fuente por usuario

votos
1

Puede eliminar por: // Esta es la función de la limpieza:

void cleantree(tree *root){
 if(root->left!=NULL)cleantree(root->left);
 if(root->right!=NULL)cleantree(root->right);
 delete root;}

// Aquí es donde llamamos a la función de limpieza:

cleantree(a);
a=NULL;

// donde "a" es puntero a la raíz del árbol.

Respondida el 24/01/2015 a las 06:39
fuente por usuario

votos
0

Respuesta corta: la implementación del descriptor de nodo falta la aplicación correcta destructor explícito (el valor predeterminado generado por el compilador será utilizada mediante una llamada al operador delete: llamando al destructor y liberando el espacio asignado en el montón) -la que claras referencias a la hermanos

Respondida el 04/06/2016 a las 21:39
fuente por usuario

votos
-1

aquí está mi sugerencia usando recursividad ..

 template <class T> void Tree<T>::destroy(Noeud<T> ** r){

            if(*r){
                if(!(*r)->left && !(*r)->right){  //a node having no child
                  delete *r; *r=NULL;
                }else if((*r)->left && (*r)->right){ //a node having two childs
                    destroy(&(*r)->left); //destroy the left tree
                    destroy(&(*r)->right); //destroy the right tree
                    destroy(r); //destroy the node
                }else if((*r)->left){ //a node has only left child
                    destroy(&(*r)->left); //destroy the left tree
                    destroy(r); //destroy the node
                }else if((*r)->right){ //a node has only right child
                    destroy(&(*r)->right); //destroy the right tree
                    destroy(r); //destroy the node
                }
            }
}

//in function main()
int main(){
Tree<int> a(5); // 'a' is a tree of int type with a root value equal 5
a.add(2);a.add(7);a.add(6);a.add(-1);a.add(10); // insert values into the tree 
a.destroy(&a.root);  //destroy the tree
}
Respondida el 06/02/2017 a las 14:28
fuente por usuario

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more