Create ABB iteratively C ++

1

I have the following code that compiles perfect, but when executing and printing the tree, it is empty.

void arbol::ArbolBusqI(string x, pnodo& nuevo)
{
    pnodo ptr = nuevo;
    for (;;)
  {
        if (ptr == NULL)
        {
            ptr = new nodoArbol();
            ptr->info = x;
            ptr->izq=ptr->der=NULL;
            ptr->repe=1;
            return; 
        }
        else
        {
            if (ptr->info==x)
            {
                ptr->repe++;
                return;
            }
            if (x < ptr->info)
                ptr = ptr->izq;
            if (x > ptr->info)
                ptr = ptr->der;
    }
  }
}

pnodo is a data type that basically is a pointer to a tree node. When a repeated data is entered, the repetition of the node (int repe) is increased by 1

    
asked by sarquis88 25.05.2017 в 02:34
source

1 answer

0

In the following fragment you create a new node for the tree ...

if (ptr == NULL)
{
  ptr = new nodoArbol();
  ptr->info = x;
  ptr->izq=ptr->der=NULL;
  ptr->repe=1;
  return; 
}

... but if you notice you are not including that node in the tree, so it will always be empty.

To add the node to the tree you need to keep a pointer to the parent node. If you can afford to edit the constructors of the objects, the best thing to do is, first of all, touch the constructor to leave its member variables initialized:

struct nodoArbol
{
  nodoArbol(std::string const& info)
    : info(info), izq(0), der(0), repe(1)
  { }

  // ...
};

If you can not do this then the ideal is to enable a function that does just that:

pnodo NuevoNodo(std::string const& info)
{
  pnodo nodo = new nodoArbol(x);
  nodo->info = info;
  nodo->izq = 0;
  nodo->der = 0;
  nodo->repe = 1;
}

And now we can modify the function so that the nodes can be added to the tree:

if( nuevo == 0 )
  nuevo = new nodoArbol(x);
else
{
  pnodo ptr = nuevo;
  while( true )
  {
    if( x == ptr->info )
    {
      nuevo->repe++;
      return;
    }
    else if( ptr->info > x )
    {
      if( ptr->izq )
        ptr = ptr->izq;
      else
      {
        ptr->izq = new nodoArbol(x);
        return;
      }
    } else { // ptr->info < x
      if( ptr->der)
        ptr = ptr->der;
      else
      {
        ptr->der= new nodoArbol(x);
        return;
      }
    }
  }
}
    
answered by 25.05.2017 / 10:49
source