You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.8 KiB
C++

#include "BinarySearchTree.h"
using namespace std;
Node * walk_tree(string key, Node *n) {
if (n->get_key() == key)
return n;
if (n->get_key() > key) {
if (n->get_left_child() != NULL)
return walk_tree(key, n->get_left_child());
return n;
}
if (n->get_right_child() != NULL)
return walk_tree(key, n->get_right_child());
return n;
}
Node * BinarySearchTree::search(string key) {
if (this->root == NULL)
return NULL;
Node * t_node = walk_tree(key, this->root);
if (t_node->get_key() != key)
return NULL;
else
return t_node;
}
int BinarySearchTree::insert(string key) {
if (this->root == NULL) {
Node * new_node = new Node(key);
this->root = new_node;
return 0;
}
if (BinarySearchTree::search(key) != NULL)
return 0;
Node * t_node = walk_tree(key, this->root);
t_node->insert(key);
return 0;
}
void inOrderTreePrint(Node *n) {
if (n != NULL) {
inOrderTreePrint(n->get_left_child());
cout << n->get_key() << ", ";
inOrderTreePrint(n->get_right_child());
}
}
void BinarySearchTree::list() {
cout << "All keys in ascending order:" << endl;
inOrderTreePrint(this->root);
cout << "(end)" << endl;
// mit der inOrderTreePrint Methode fällt mir gerade kein
// eleganter Weg ein, um das letzte Komma weglassen zu können.
// also füge ich das "(end)" am Ende hinzu, damit es zumindest nicht
// so unvollständig aussieht.
}
void delete_rec(Node * n) {
if (n->get_left_child() != NULL)
delete_rec(n->get_left_child());
if (n->get_right_child() != NULL)
delete_rec(n->get_right_child());
delete n;
}
BinarySearchTree::~BinarySearchTree() {
if (this->root == NULL)
return;
delete_rec(this->root);
}