What I have done is as below, but with this I am having a lot of problems while destructing the tree, and while trying to print the tree (basically anywhere I need to use recursion on the tree).
This is because while trying to call print
recursively on the left of the right subtrees, my method breaks because my left and right subtrees are actually only Node
s and not Tree
s. So, I need to either typecase my Nodes to Trees or I need to create new trees, both of which are ugly solutions.
I think the problem here is with class design. Can you please comment on the same? Thanks!
class Node {
int _data;
public:
Node* left; // left child
Node* right; // right child
Node* p; // parent
Node(int data) {
_data = data;
left = NULL;
right = NULL;
p = NULL;
}
~Node() {
}
int d() {
return _data;
}
void print() {
std::cout << _data << std::endl;
}
};
class Tree {
Node* root;
public:
Tree() {
root = NULL;
}
Tree(Node* node) {
root = node;
}
~Tree() {
delete root->left; // this is NOT RIGHT as
// it only deletes the node
// and not the whole left subtree
delete root->right;
delete root;
}
void print(int);
void add(int);
};
Why don't you just allow Node
to be your tree class? A non-empty node, by definition, is the root of some tree. This will substantially simplify your code since you don't need to make different cases for Tree
and Node
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With