Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to design C++ tree and node classes? [closed]

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 Nodes and not Trees. 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);
};
like image 756
Moeb Avatar asked Dec 16 '22 18:12

Moeb


1 Answers

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.

like image 105
nneonneo Avatar answered Dec 24 '22 04:12

nneonneo