ayudar con la inserción en la primera BST

votos
1

EDITAR hay una pequeña cosa que me falta !! el error sigue ahí

Así que estoy tratando de aprender cómo codificar mi primer BST, y es difícil .... ya estoy teniendo problemas con sólo unas pocas líneas de código. el problema está en el inserto, pero he incluido todo para que pudiera obtener alguna información sobre mi estilo / otros errores. Me sugiere utilizar un puntero a puntero de aplicación, pero que no hemos aprendido todavía, así que no sentirá la comodidad / saber cómo codificar todavía. el

error es

[trinhc@cs1 Assignment_3]$ g++ movieList.cpp -o a.out
/tmp/ccLw6nsv.o: In function `main':
movieList.cpp:(.text+0x7a): undefined reference to `Tree::Tree()'
movieList.cpp:(.text+0xa7): undefined reference to `Tree::insert(int, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2: ld returned 1 exit status

el archivo tree.h

#ifndef TREE_H
#define TREE_H

#include <string>
#include <iostream>
using namespace std;

class Tree
{
 public:
  Tree();
  bool insert(int k, string s);

 private:
  struct Node
  {
    int key;
    string data;
    Node *left;
    Node *right;
  };
  Node* root;
  bool insert(Node*& root, int k, string s);
};

#endif

tree.cpp

#include <iostream>
#include tree.h
#include <stack>
#include <queue>
#include <string>
using namespace std;

Tree::Tree()
{
  root = NULL;
}

bool Tree::insert(int k, string s)
{
  return insert(root, k, s);
}

bool Tree::insert(Node*& current_root, int k, string s)
{
  if(root == NULL){
    current_root = new Node;
    current_root->key = k;
    current_root->data = s;
    current_root->left = NULL;
    current_root->right = NULL;
    return true;
  }
  else if (current_root->key == k)
    return false;
  else if (current_root->key > k)
    insert(current_root->left, k, s);
  else
    insert (current_root->right,k, s);
}

movieList.cpp

#include <iostream>
#include <stack>
#include <queue>
#include <string>
#include tree.h


using namespace std;

int main()
{
  Tree test;
  test.insert(100, blah);
  return 0;
}
Publicado el 27/04/2011 a las 03:15
fuente por usuario
En otros idiomas...                            


4 respuestas

votos
2

prueba de árbol (); no es cómo definir un objeto de la clase Test, Este declarar; fuimos de test denominada función que devuelve árbol.

tratar

prueba de árbol; test.instert (100, "bla"); return 0;

Respondida el 27/04/2011 a las 03:34
fuente por usuario

votos
1

Un par de puntos:

Es necesario cambiar el nombre de su miembro de la raíz variable para algo else- Me gustaría recomendar m_root o my_root o tree_root, o algo de ese tipo. Ahora usted tiene un poco de un choque espacio de nombres en cualquier función en la que incluyen la raíz como un argumento. Esto también le permitirá mantener un registro de qué raíz que usted se refiere.

bool Tree::insert(Node*& root, int k, string s)
{
    if(root == NULL){
        root = new Node;
        root->key = k;
        root->data = s;
        root->left = NULL;
        root->right = NULL;
        return true;
    } else
        if (root == k) //Comparison between pointer and number.
            return false;
        else
            if (root->key > k)
                insert(root->left, k, s);
            else
                insert (root->right,k, s);
    }

Es necesario cambiar de raíz en la línea comentada a Raíz> llave.

Aparte de eso, parece que va a trabajar.

EDIT: Además, lo que dijo el otro tipo. Se declara un objeto como

TYPE name ()

si llama al constructor por defecto (), por lo que su código en su función principal debe ser

Tree test;
test.insert(...)
Respondida el 27/04/2011 a las 03:38
fuente por usuario

votos
1

He copiado algunos de su código y esto está trabajando muy bien para mí:

principal:

#include <iostream>
#include <stack>
#include <queue>
#include <string>
#include "tree.h"

    int main()
    {
      Tree test;
      test.insert(100, "blah");
      test.insert(50, "fifty");
      test.insert(110, "one hundred ten");
      return 0;
    }

Función de inserción:

bool Tree::insert(Node*& currentRoot, int k, string s)
{
  if(currentRoot == NULL){
    currentRoot = new Node;
    currentRoot->key = k;
    currentRoot->data = s;
    currentRoot->left = NULL;
    currentRoot->right = NULL;
    return true;
  }
  else if (currentRoot->key == k)
    return false;
  else if (currentRoot->key > k)
    insert(currentRoot->left, k, s);
  else
    insert (currentRoot->right,k, s);
}

Aparte de eso tiene errores de sintaxis por todo el lugar. También ha cambiado el nombre porque, como alguien señaló que había un poco de un problema de nomenclatura. CurrentRoot tiene sentido porque está de paso que la raíz del subárbol izquierdo o derecho en cada recursividad.

Respondida el 27/04/2011 a las 03:39
fuente por usuario

votos
0

¿No debería añadir tree.cppa su comando de construcción?

[Trinhc @ CS1 Assignment_3] $ g ++ movieList.cpp -o a.out

Se convertiría

[Trinhc @ CS1 Assignment_3] $ g ++ tree.cpp movieList.cpp -o a.out

Respondida el 27/04/2011 a las 05:01
fuente por usuario

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