Binary Search Tree Issue in C++ - c++

i am creating a binary search tree, and here is my code for the TreeDB.cpp file:
TreeDB::TreeDB()
{
root = NULL;
}
bool TreeDB::insert(DBentry * _entry)
{
if (root == NULL)
{
root = new TreeNode(_entry);
root->setLeft(NULL);
root->setRight(NULL);
cout <<"Inserted at root";
}
else
{
insert_helper(root,_entry);
}
}
bool TreeDB::insert_helper(TreeNode *curr, DBentry * _entry)
{
string temp1 = curr->getEntry()->getName();
string temp2 = _entry-> getName();
if(temp1 == temp2)
{
cout <<"Error: entry already exists"<<endl;
delete _entry;
return false;
}
else if(temp1<temp2)
{
if(curr->getRight() == NULL)
{
curr->setRight(new TreeNode(_entry));
cout << "Set right";
return true;
}
else
{
insert_helper(curr->getRight(),_entry);
}
}
else
{
if(curr->getLeft() == NULL)
{
curr->setLeft(new TreeNode(_entry));
cout <<"Set Left";
return true;
}
else
{
insert_helper(curr->getLeft(),_entry);
}
}
}
and my header file is Tree.h:
class TreeDB {
private:
TreeNode* root;
int probesCount;
public:
TreeDB();
~TreeDB();
bool insert(DBentry* newEntry);
bool insert_helper(TreeNode*curr,DBentry*_entry);
};
And i am also creating the object of this tree in main like so:
TreeDB Tree;
while (!lineStream.eof())
{
if (command == "insert")
{
unsigned int address;
string name;
bool active;
lineStream >> name >> address >> active;
DBentry * a = new DBentry(name,address,active);
Tree.insert(a);
}
However, every time i try to insert something, it always inserts at the root, so either the previous one never gets saved or it gets deleted after each insert. Any hints as to how i can resolve this issue?

Related

C++ tree data structure Access violation with String

I am trying to make a tree data structure with c++. Originally I tested with int data, it was going fine. However, when I try to use a string data type, it keeps showing an unhandled exception. It said read access violation, this was 0x5D. I don't know what is causing the error. The complete same code only changing int to string causes the violation.
Main:
#include <bits/stdc++.h>
#include "Tree.h"
using namespace std;
int main()
{
Tree A;
int choice; bool isCre=0;
cout << "Input choice : ";
while (cin >> choice) {
switch (choice)
{
case 1:
if (!isCre) {
A.create_tree(); isCre = 1;
break;
}
else {
A.add_tree();
break;
}
case 2:
A.delete_tree(); break;
case 3:
A.modify_tree(); break;
case 4:
A.display_tree(); break;
}
cout << "Input choice : ";
}
}
Header file:
#ifndef TREE_H
#define TREE_H
#include <bits/stdc++.h>
using namespace std;
class Tree
{
private:
struct Tre
{
Tre* parent; Tre* right; Tre* left;
string data;
Tre(Tre* parent, string data)
{
this->parent = parent;
this->data = data;
left = right = NULL;
}
};
Tre* root;
Tre* create(Tre*& root, string data)
{
Tre* p;
p = new Tre(NULL, data);
root = p;
return root;
}
void dis(Tre* node)
{
if (node == NULL)
return;
cout << node->data << endl;
dis(node->left);
dis(node->right);
}
Tre* search(Tre* node, string data)
{
if (node == NULL)
return NULL;
if (node != NULL && node->data == data)
return node;
/* then recur on left subtree */
Tre* p = search(node->left, data);
// node found, no need to look further
if (p != NULL && p->data == data) return p;
/* node is not found in left,
so recur on right subtree */
Tre* q = search(node->right, data);
if (q != NULL && q->data == data) return q;
}
Tre* add(Tre* root, string find, string input)
{
Tre* p = root;
p = search(root, find);
if (p->left != NULL)
{
p->right = new Tre(p, input);
//p->left = new Tre(p, input);
}
else if (p->left == NULL)
{
p->left = new Tre(p, input);
//p->right = new Tre(p, input);
}
return root;
}
Tre* del(Tre* root, string data)
{
Tre* p = root, * q;
p = search(root, data);
q = p->parent;
if (q->right != NULL && q->right->data == data)
{
q->right = NULL;
delete p;
}
else if (q->left->data == data)
{
q->left = NULL;
delete p;
}
return root;
}
Tre* modify(Tre* root, string find, string input)
{
Tre* p = root;
p = search(p, find);
p->data = input;
return root;
}
public:
void create_tree();
void display_tree();
void add_tree();
void delete_tree();
void modify_tree();
};
#endif
#endif
Implementation file:
#include "Tree.h"
void Tree::create_tree()
{
string data;
cout << "Input data : "; cin >> data;
create(root, data);
}
void Tree::display_tree()
{
dis(root);
}
void Tree::add_tree()
{
string find, input;
cout << "Parent data : "; cin >> find;
cout << "New data : "; cin >> input;
add(root, find, input);
}
void Tree::delete_tree()
{
string data;
cout << "Delete data : "; cin >> data;
del(root, data);
}
void Tree::modify_tree()
{
string find, input;
cout << "Find data : "; cin >> find;
cout << "New data : "; cin >> input;
modify(root, find, input);
}

Cannot find source of segmentation fault

I have been working on this assignment for sometime and cannot figure out what is causing the segmentation fault, any help would be appreciated, here is a copy of my two files!
I am also in the process of fixing my inFile setup, but I would rather focus on that after the fact of the segmentation error.
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include "source.cpp"
using namespace std;
void scanFile(string fileName);
void printActors(string movie);
void printShows(string actor);
const int MAX_LINE = 128;
int movies = 0;
BST tree;
int main(){
// Scan file
scanFile("tvDB.txt");
// Print all the show titles
cout << "All show titles:" << endl;
tree.displayShows();
cout << endl; // Whitespace
// Print actors /w given show
cout << "Actors from 'The Saint'" << endl;
printActors("The Saint");
// Print show /w given actor
printShows("Tim Conway");
// Print from decade
return 0;
}
// Trims the line removing all excess whitespace before and after a sentence
string isolateLine(string line)
{
int index = 0, start = 0, end = 0;
//Get the start of the line
for(int i = 0; i < line.length(); i++)
{
if(line[i] != ' ' && line[i] != '\t')
{
start = i;
break;
}
}
// Get the end of the line
for(int x = line.length(); x >= 0; x--)
{
if(line[x] != ' ' && line[x] != '\t')
{
end = x;
break;
}
}
// Trim line
line = line.substr(start, end);
return line;
}
// A boolean that returns if the tree is blank, useful for skipping a line and continuing to search for a movie
bool blankLine(string line){
for(int i = 0; i < line.length(); i++)
{
if(line[i] != ' ' && line[i] != '\t')
{
return false;
}
}
return true;
}
// Prints all the shows an actor has starred in
void printShows(string actor){
cout << "Shows with [" << actor << "]:" << endl;
tree.displayActorsShows(actor);
cout << endl; // whitespace
}
// Prints all the actors in a particular movie
void printActors(string show)
{
cout << " Actors for [" << show << "]" << endl;
tree.displayActors(show);
cout << endl;
}
// Scans the fild and categorizes every line of data into the proper categories of the show
void scanFile(string fileName)
{
ifstream inFile;
inFile.open("tvDB.txt");
list <string> actors;
string line = "";
string title = "";
string year = "";
while(getline(inFile, line))
{
line = isolateLine(line);
if(!blankLine(line))
{
// Get movie title
if(line.find('(') != std::string::npos)
{
title = line.substr(0, line.find('(')-1);
}
// Get movie year
if (line.find('(') != std::string::npos) {
year = line.substr(line.find('(') + 1, line.find(')'));
year = year.substr(0, year.find(')'));
}
// Add to actors list
actors.push_back(line);
}
else
{
if(!actors.empty()) // pops the title
{
actors.pop_front();
}
}
tree.insert(title, year, actors);
actors.clear();
movies++;
}
}
and
#include <iostream>
#include <list>
using namespace std;
class BST
{
// Defines the main components of the node object, as well as refrences the left and right elements
struct node
{
string show;
string year;
string genre;
string URL;
list <string> actors;
node*left;
node*right;
};
node* root;
// Deletes all the nodes of the tree
node* makeEmpty(node* t)
{
if(t == NULL)
{
return NULL;
}
else
{
makeEmpty(t->left);
makeEmpty(t->right);
delete t;
}
return NULL;
}
// Inserts a node in the tree
node* insert(string x, string year, list<string> actors, node* t)// DO not include Genrem or URL
{
if(t == NULL)
{
t = new node;
t->show = x;
t->year = year;
t->actors = actors;
t->left = t->right = NULL;
}
else if(x < t-> show)
{
t->left = insert(x, year, actors, t->left);
}
else if(x > t-> show)
{
t->right = insert(x, year, actors, t->left);
}
else
{
return t;
}
}
//Finds the minimum most node to the left
node* findMin(node* t)
{
if(t == NULL)
{
return NULL;
}
else if(t->left == NULL)
{
return t;
}
else
{
return findMin(t->left);
}
}
// Finds the maximum most node to the right
node* findMax(node* t)
{
if(t == NULL)
{
return NULL;
}
else if(t->right == NULL)
{
return t;
}
else
{
return findMax(t->right);
}
}
// Finds a node with the given parameters
node* find(node* t, string x )
{
if(t == NULL)
{
return NULL;
}
else if(x.at(0) < t-> show.at(0))
{
return find(t->left, x);
}
else if(x.at(0) > t->show.at(0))
{
return find(t->right, x);
}
else
{
return t;
}
}
// Prints out the shows inorder
void inorder(node* t)
{
if(t == NULL)
{
// Do nothing
}
else
{
inorder(t->left);
cout << "- " << t->show << endl;
inorder(t->right);
}
}
// Prints the shows of a given actor
void findShow(node* t, string person, list<string> &list)
{
if(t == NULL)
{
// Do nothing
}
else
{
while(!t->actors.empty())
{
if(t->actors.front() == person)
{
list.push_front(t->show);
break;
}
t->actors.pop_front();
}
findShow(t->left, person, list);
findShow(t->right, person, list);
}
}
// Prints the shows within a given year
void findYear(node* t, string year, list<string> &list)
{
if(t == NULL)
{
// Do nothing
}
else
{
if(t->year == year)
{
list.push_front(t->show);
}
findYear(t->left, year, list);
findYear(t->right, year, list);
}
}
public:
BST()
{
root = NULL;
}
~BST()
{
root = makeEmpty(root);
}
// Public calls to modify the tree
// Inserts a node with the given parametersremove
void insert(string x, string year, list<string> actors)
{
root = insert(x, year, actors, root);
}
// Removes a node with the given key
// void remove(string x, node* t)
// {
// root = remove(x, root);
// }
// Displays all shows within the tree
void displayShows()
{
inorder(root);
}
// Displays all the actors with a given show
void displayActors(string show)
{
root = find(root, show);
if(root != NULL) // THIS LINE
{
list<string> temp = root-> actors;
while(!temp.empty())
{
cout << "- " << temp.front() << endl;
temp.pop_front();
}
}
else
{
cout << "root is NULL." << endl;
}
}
// Displays the shows of a given actor
void displayActorsShows(string actor)
{
list<string> show;
findShow(root, actor, show);
while(!show.empty())
{
cout << "- " << show.front() << endl;
show.pop_front();
}
}
// Searches the tree with the given node
void search(string x)
{
root = find(root, x);
}
};// end of class
I would suggest using a debugger (like GDB for unix or the VisualStudioBuildIn Debugger). There the SEG Fault is indicated in which variable the seg fault will be.
Also look out for correct initialized pointers (at least with = nullptr)
Btw: try to use nullptr instead of NULL, since it is not typesafe to use NULL.
Here is why: NULL vs nullptr (Why was it replaced?)

Cannot figure out constructor errors

I have come across a couple of compiler errors in my code where it is saying. I have been working on this assignment and these seem to be the last two errors that I am comming across and would love some help on why it will not compile, I just want to go to bed :(
main.cpp:103:29: error: in c++98 'actors' must be initialized by constructor, not by '{...}'
list<string> actors = {};
and
main.cpp:138:19: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default]
actors = {};
Below is a copy of my two files! Thank you!
#include <iostream>
#include <list>
using namespace std;
class BST
{
// Defines the main components of the node object, as well as refrences the left and right elements
struct node
{
string show;
string year;
string genre;
string URL;
list <string> actors;
node*left;
node*right;
};
node* root;
// Deletes all the nodes of the tree
node* makeEmpty(node* t)
{
if(t == NULL)
{
return NULL;
}
else
{
makeEmpty(t->left);
makeEmpty(t->right);
delete t;
}
return NULL;
}
// Inserts a node in the tree
node* insert(string x, string year, list<string> actors, node* t)// DO not include Genrem or URL
{
if(t == NULL)
{
t = new node;
t->show = x;
t->year = year;
t->actors = actors;
t->left = t->right = NULL;
}
else if(x < t-> show)
{
t->left = insert(x, year, actors, t->left);
}
else if(x > t-> show)
{
t->right = insert(x, year, actors, t->left);
}
else
{
return t;
}
}
//Finds the minimum most node to the left
node* findMin(node* t)
{
if(t == NULL)
{
return NULL;
}
else if(t->left == NULL)
{
return t;
}
else
{
return findMin(t->left);
}
}
// Finds the maximum most node to the right
node* findMax(node* t)
{
if(t == NULL)
{
return NULL;
}
else if(t->right == NULL)
{
return t;
}
else
{
return findMax(t->right);
}
}
// Finds a node with the given parameters
node* find(node* t, string x )
{
if(t == NULL)
{
return NULL;
}
else if(x.at(0) < t-> show.at(0))
{
return find(t->left, x);
}
else if(x.at(0) > t->show.at(0))
{
return find(t->right, x);
}
else
{
return t;
}
}
// Prints out the shows inorder
void inorder(node* t)
{
if(t == NULL)
{
// Do nothing
}
else
{
inorder(t->left);
cout << "- " << t->show << endl;
inorder(t->right);
}
}
// Prints the shows of a given actor
void findShow(node* t, string person, list<string> &list)
{
if(t == NULL)
{
// Do nothing
}
else
{
while(!t->actors.empty())
{
if(t->actors.front() == person)
{
list.push_front(t->show);
break;
}
t->actors.pop_front();
}
findShow(t->left, person, list);
findShow(t->right, person, list);
}
}
// Prints the shows within a given year
void findYear(node* t, string year, list<string> &list)
{
if(t == NULL)
{
// Do nothing
}
else
{
if(t->year == year)
{
list.push_front(t->show);
}
findYear(t->left, year, list);
findYear(t->right, year, list);
}
}
public:
BST()
{
root = NULL;
}
~BST()
{
root = makeEmpty(root);
}
// Public calls to modify the tree
// Inserts a node with the given parametersremove
void insert(string x, string year, list<string> actors)
{
root = insert(x, year, actors, root);
}
// Removes a node with the given key
// void remove(string x, node* t)
// {
// root = remove(x, root);
// }
// Displays all shows within the tree
void displayShows()
{
inorder(root);
}
// Displays all the actors with a given show
void displayActors(string show)
{
root = find(root, show);
if(root != NULL) // THIS LINE
{
list<string> temp = root-> actors;
while(!temp.empty())
{
cout << "- " << temp.front() << endl;
temp.pop_front();
}
}
else
{
cout << "root is NULL." << endl;
}
}
// Displays the shows of a given actor
void displayActorsShows(string actor)
{
list<string> show;
findShow(root, actor, show);
while(!show.empty())
{
cout << "- " << show.front() << endl;
show.pop_front();
}
}
// Searches the tree with the given node
void search(string x)
{
root = find(root, x);
}
};// end of class
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include "source.cpp"
using namespace std;
void scanFile(string fileName);
void printActors(string movie);
void printShows(string actor);
const int MAX_LINE = 128;
int movies = 0;
BST tree;
int main(){
// Scan file
scanFile("tvDB.txt");
// Print all the show titles
cout << "All show titles:" << endl;
tree.displayShows();
cout << endl; // Whitespace
// Print actors /w given show
cout << "Actors from 'The Saint'" << endl;
printActors("The Saint");
// Print show /w given actor
printShows("Tim Conway");
// Print from decade
return 0;
}
// Trims the line removing all excess whitespace before and after a sentence
string isolateLine(string line)
{
int index = 0, start = 0, end = 0;
//Get the start of the line
for(int i = 0; i < line.length(); i++)
{
if(line[i] != ' ' && line[i] != '\t')
{
start = i;
break;
}
}
// Get the end of the line
for(int x = line.length(); x >= 0; x--)
{
if(line[x] != ' ' && line[x] != '\t')
{
end = x;
break;
}
}
// Trim line
line = line.substr(start, end);
return line;
}
// A boolean that returns if the tree is blank, useful for skipping a line and continuing to search for a movie
bool blankLine(string line){
for(int i = 0; i < line.length(); i++)
{
if(line[i] != ' ' && line[i] != '\t')
{
return false;
}
}
return true;
}
// Prints all the shows an actor has starred in
void printShows(string actor){
cout << "Shows with [" << actor << "]:" << endl;
tree.displayActorsShows(actor);
cout << endl; // whitespace
}
// Prints all the actors in a particular movie
void printActors(string show)
{
cout << " Actors for [" << show << "]" << endl;
tree.displayActors(show);
cout << endl;
}
// Scans the fild and categorizes every line of data into the proper categories of the show
void scanFile(string fileName)
{
ifstream inFile;
inFile.open("tvDB.txt");
list <string> actors = {};
string line = "";
string title = "";
string year = "";
while(getline(inFile, line))
{
line = isolateLine(line);
if(!blankLine(line))
{
// Get movie title
if(line.find('(') != std::string::npos)
{
title = line.substr(0, line.find('(')-1);
}
// Get movie year
if (line.find('(') != std::string::npos) {
year = line.substr(line.find('(') + 1, line.find(')'));
year = year.substr(0, year.find(')'));
}
// Add to actors list
actors.push_back(line);
}
else
{
if(!actors.empty()) // pops the title
{
actors.pop_front();
}
}
tree.insert(title, year, actors);
actors = {};
movies++;
}
}
You have two options in this case:
Using C++11 is acceptable, in that case you can leave the code as-is but add -std=c++11 to your compilation flags (e.g. in your Makefile).
Replace usage of the initializer list:
list <string> actors = {}; -> list <string> actors; (documentation)
actors = {}; -> actors.clear(); (documentation)

difficulty inserting into binary search tree

I am currently learning C++ and have been researching BST. I took upon myself a task within a workbook but have been struggling to finish the implementation.
I am not allowed to change the header file or any of the function definitions but I am allowed to add helpers.
I have attempted adding some helpers, but whenever I run the test file, no words are inserted into the tree.
I was hoping someone would be able to help me or give me guidance on finishing the implementation.
Any help on the other functions would be greatly appreciated!
My Header File:
#pragma once
#include <iostream>
#include <string>
// Node of the tree
struct Node
{
std::string data;
Node *left = nullptr;
Node *right = nullptr;
};
class BST
{
private:
Node *root = nullptr;
public:
BST();
BST(std::string word);
BST(const BST &rhs);
~BST();
void insert(std::string word);
void remove(std::string word);
bool exists(std::string word) const;
std::string inorder() const;
std::string preorder() const;
std::string postorder() const;
bool operator==(const BST &other) const;
bool operator!=(const BST &other) const;
};
My BST file:
#include "bst.h"
#include <iostream>
#include <string>
using namespace std;
string HelperInsert(Node **root, std::string word)
{
if (*root == nullptr)
{
// Create new node
*root = new Node;
// Set new value
(*root)->data = word;
// Set branches to nullptr
(*root)->left = nullptr;
(*root)->right = nullptr;
}
else
if (word < (*root)->data)
{
HelperInsert(&(*root)->left, word);
}
else
{
if (word > (*root)->data)
{
HelperInsert(&(*root)->right, word);
}
}
}
void HelperExists(Node *root, string word)
{
Node *temp = new Node;
temp = root;
// Run the loop untill temp points to a NULL pointer.
while(temp != NULL)
{
if(temp->data == word)
{
cout<<"True "<<endl;
}
// Shift pointer to left child.
else if(temp->data > word)
temp = temp->left;
// Shift pointer to right child.
else
temp = temp->right;
}
cout<<"\n False";
return;
}
string Helpwr(Node *root)
{
if(root == nullptr)
{
return "";
}
else
{
return inorderHelper(root->left)
+ root->data + " "
+ inorderHelper(root->right);
}
}
void HelperPreOrder(Node *root)
{
if ( root !=nullptr)
{
cout << root->data << " ";
HelperPreOrder(root->left);
HelperPreOrder(root->right);
}
}
void HelperPostorder(Node *root)
{
if (root!=nullptr)
{
HelperPostorder(root->left);
HelperPostorder(root->right);
cout << root->data<< endl;
return;
}
}
BST::BST()
{
root= nullptr;
}
// Creates a binary tree by copying an existing tree
BST::BST(const BST &rhs)
{
}
void BST::insert(string word)
{
HelperInsert(*root, word);
}
void BST::remove(string word)
{
}
bool BST::exists(string word) const
{
HelperExists(root, word);
return true;
}
std::string BST::inorder() const
{
string res = inorderHelper(root);
int len = res.length();
if(len >= 1 && res[len -1] == ' ')
{
res.pop_back();
}
return res;
}
std::string BST::preorder() const
{
HelperPreOrder(root);
return std::string("");
}
std::string BST::postorder() const
{
HelperPostorder(root);
return std::string("");
}
bool BST::operator==(const BST &other) const
{
return true;
}
bool BST::operator!=(const BST &other) const
{
return true;
}
My test file:
tree = new BinarySearchTree();
// Test 3 - insertion check
tree->insert("fish");
tree->insert("aardvark");
tree->insert("zeebra");
str = tree->inorder();
if (str != string("aardvark fish zeebra"))
cerr << "test 3 failed" << endl;
else
cout << "Test 3 passed" << endl;
// Test 4 - exists check
if (tree->exists("zeebra") && tree->exists("fish") && !tree->exists("bird") && !tree->exists("snake"))
cout << "Test 4 passed" << endl;
else
cerr << "test 4 failed" << endl;
Seems like an issue of not storing the string words correctly:
your insert method is as follows:
void insert(std::string word);
Which means a value of the string is passed, not a reference.
In order to store the string, you'll have to create a copy of the string and store it in memory:
string HelperInsert(Node **root, std::string word)
{
if (*root == nullptr)
{
// Create new node
*root = new Node;
// Set new value
(*root).data = new std:string(word); // note the setting of a string pointer here!
// Set branches to nullptr
(*root)->left = nullptr;
(*root)->right = nullptr;
}
else
if (word < (*root)->data)
{
HelperInsert(&(*root)->left, word);
}
else
{
if (word > (*root)->data)
{
HelperInsert(&(*root)->right, word);
}
}
}
Do not forget to delete the string when removing nodes, in order to prevent mempory leaks.
Good luck!

A ton of undefined reference errors

I don't know if I'm linking wrong but I'm compiling this on linux and I'm getting a LOT of undefined references for my node functions. I'm writing a binary search tree to searches for telephones for class that is due tonight.
bst.cpp
#include "bst.hpp"
BST::BST(void)
{
count = 0;
root = NULL;
}
void BST::insert(long long x, string y)
{
Node *newnode = new Node(x, y);
Node *temp;
if (count == 0)
{
root = newnode;
count++;
}
else
{
while(temp->getleft() != NULL && temp->getright() != NULL)
{
if(newnode->getnum() < temp->getnum())
{
temp = temp->getleft();
}
else
{
temp = temp->getright();
}
}
if (newnode->getnum() < temp->getnum())
{
temp->setleft(newnode);
}
else
{
temp->setright(newnode);
}
}
}
Node * BST::getroot(void)
{
return root;
}
Node* BST::delete_node(Node *troot, long long key)
{
if (count == 0)
{
return troot;
}
else if(key < troot->getnum())
{
delete_node(troot->getleft(), key);
}
else if (key > troot->getnum())
{
delete_node(troot->getright(), key);
}
else
{
if(troot->getleft() == NULL && troot->getright() == NULL)
{
delete troot;
troot == NULL;
}
else if(troot->getright() == NULL)
{
Node *temp = troot;
troot = troot->getleft();
delete temp;
}
else if(troot->getleft() == NULL)
{
Node *temp = troot;
troot = troot->getright();
delete temp;
}
}
return troot;
}
void BST::preverse(Node* troot)
{
if(root == NULL)
{
cout << "The tree is empty\n";
}
if(troot == NULL)
{
return;
}
cout << troot->getname() << endl;
cout << troot->getnum() << endl;
preverse(troot->getleft());
preverse(troot->getright());
}
void BST::postverse(Node* troot)
{
if(root == NULL)
{
cout << "The tree is empty\n";
}
if(troot == NULL)
{
return;
}
postverse(troot->getleft());
postverse(troot->getright());
cout << troot->getname() << endl;
cout << troot->getnum() << endl;
}
void BST::inverse(Node* troot)
{
if(root == NULL)
{
cout << "The tree is empty\n";
}
if(troot == NULL)
{
return;
}
inverse(troot->getleft());
cout << troot->getname() << endl;
cout << troot->getnum() << endl;
inverse(troot->getright());
}
void BST::search(Node* troot, long long key)
{
if(root == NULL)
{
cout << "The tree is empty\n";
}
if(troot == NULL)
{
return;
}
if(key == troot->getnum())
{
cout << troot->getname();
}
search(troot->getleft(), key);
search(troot->getright(), key);
}
bst.hpp
#include "node.hpp"
#ifndef bst_hpp
#define bst_hpp
class BST
{
Node* root;
long long count;
public:
BST(void);
void insert(long long x, string y);
Node* getroot(void);
Node* delete_node(Node* troot, long long key);
void preverse(Node* troot);
void postverse(Node* troot);
void inverse(Node* troot);
void search(Node* troot, long long key);
};
#endif
node.cpp
#include "node.hpp"
Node::Node(void)
{
number = 0;
name = "no name";
left = NULL;
right = NULL;
}
Node::Node(long long t, string n)
{
number = t;
name = n;
left = NULL;
right = NULL;
}
Node * Node::getleft(void)
{
return left;
}
Node * Node::getright(void)
{
return right;
}
void Node::setleft(Node * ptr)
{
left = ptr;
}
void Node::setright(Node * ptr)
{
right = ptr;
}
long long Node::getnum(void)
{
return number;
}
string Node::getname(void)
{
return name;
}
node.hpp
#ifndef node_hpp
#define node_hpp
#include <string>
#include <iostream>
using namespace std;
class Node
{
long long number;
string name;
Node *left;
Node *right;
public:
Node(void);
Node(long long t, string n);
Node* getleft(void);
Node* getright(void);
void setleft(Node* ptr);
void setright(Node* ptr);
long long getnum(void);
string getname(void);
};
#endif
main.cpp
#include "bst.hpp"
using namespace std;
int main(void)
{
int choice;
long long numin;
string input;
BST phbook;
do
{
cout << "1. Insert a name and number.\n2. Delete using number.\n3. Traverse pre-order\n4. Traverse post-order\n";
cout << "5. Traverse in-order\n6. Search using number.\n6. Exit program\n";
switch(choice)
{
case 1:
cout << "Enter a name\n";
cin.ignore();
getline(cin, input);
cout << "Enter a number\n";
cin >> numin;
phbook.insert(numin, input);
break;
case 2:
cout << "Enter the phone number you'd like to delete.\n";
cin >> numin;
phbook.delete_node(phbook.getroot(), numin);
break;
case 3:
phbook.preverse(phbook.getroot());
break;
case 4:
phbook.postverse(phbook.getroot());
break;
case 5:
phbook.inverse(phbook.getroot());
break;
case 6:
cout << "Enter a phone number to search.\n";
cin >> numin;
phbook.search(phbook.getroot(),numin);
default:
numin=numin;
}
}while(choice >= 1 && choice <= 6);
return 0;
}
To me, nothing looks wrong in linking the files.
Some examples : undefined reference to Node::getnum()
undefined reference to Node::getname()
Check the order of compiled elements:
g++ node.cpp -o node.o bst.cpp -o bst.o main.cpp -o main.o
Result:
./main.o
1. Insert a name and number.
2. Delete using number.
3. Traverse pre-order
4. Traverse post-order
5. Traverse in-order
6. Search using number.
6. Exit program