I have to write a collection - binary tree, using polymorphism. Its' roots must be objects of abstract class. I have class Node and Btree, but function "add" doesn't work correct. What am I doing wrong..? Help pls
class Node {
public:
Node() {
o = nullptr;
left = nullptr;
right = nullptr;
}
Node(object* obj) {
o = obj;
left = nullptr;
right = nullptr;
}
friend class Btree;
private:
object *o;
Node *left;
Node *right;
};
class Btree {
public:
Btree() {
count = 0;
root = nullptr;
}
void deleteNotes(Node *n) {
if (!n) return;
delete n;
delete n->left;
delete n->right;
}
Node* getRoot() {
return root;
}
Node* getLeft(Node* n) {
return n->left;
}
Node* getRight(Node* n) {
return n->right;
}
object* getData(Node *n) {
return n->o;
}
void add(object *obj) {
Node *n = new Node;
n->o = obj;
if (!n) {
return;
}
insertNode(root, n);
}
void insertNode(Node *node, Node *elem) {
if (node == nullptr) node = elem;
else {
if (equal(node->o, elem->o) < 0)
insertNode(node->left, elem);
else insertNode(node->right, elem);
}
}
Node *search(object *obj) {
return searchNode(root, obj);
}
Node *searchNode(Node *node, object *obj) {
if (equal(node->o, obj) == 0) return node;
else {
if (equal(node->o, obj) < 0) {
searchNode(node->left, obj);
}
else {
searchNode(node->right, obj);
}
}
}
void show() {
showNode(root);
}
void showNode(Node *n) {
if (n != nullptr) {
showNode(n->left);
cout << n->o->uploadInString() << "\n";
showNode(n->right);
}
}
void deleteNodes(Node *n) {
if (!n) return;
delete n;
delete n->left;
delete n->right;
}
~Btree() {
deleteNodes(root);
}
private:
int count;
Node *root;
};
I have two datatypes - Integer and Date as children of class "object". I dont't know which details should I write........
CodePudding user response:
One problem is here:
void insertNode(Node *node, Node *elem) {
if (node == nullptr) node = elem;
else {
...
}
}
The first time you try to add a node, node
is equal to root
, and so it is equal to nullptr
. So this function sets node
equal to elem
, and then quits. But node
is a local variable, it belongs to the function. The function modifies the value of the variable, then the function quits and the variable is forgotten. The value of root
is still nullptr
.
There are several ways to solve this problem. Here is one:
Node* insertNode(Node *node, Node *elem) {
if (node == nullptr) return elem;
if (equal(node->o, elem->o) < 0)
node->left = MyInsertNode(node->left, elem);
else node->right = MyInsertNode(node->right, elem);
return node;
}
void add(object *obj) {
...
root = insertNode(root, n);
}
There are other problems. I advise you to work on simpler exercises (such as linked lists) for a while longer, before attempting trees.