Question

I use composite pattern to implement a tree structure. It has 3 classes: node (base class), leaf (no child class), and branch (with children class). And I have some common data put in a tree node, like the root. An example of the common data is unit choice of meter or kilometer. The common data should be accessed to all the nodes. How to implement it? Putting a pointer of the common data to all the nodes doesn't seem to be memory efficient.

Was it helpful?

Solution

One way to do this is to add a separate class for the tree, put the root pointer there, and add all the common items there as well. Then add a tree pointer to the node base class, and also add a constructor argument to point all nodes of the tree back to their tree object:

class node;
class tree {
    node *root;
    int multiplier; // e.g. 1000 for meters, 1 for kilometers
}
class node {
protected:
    tree *owner;
    node *parent; // parent is NULL for the root
    node(tree *_owner, node *_parent) : owner(_owner), parent(_parent) {}
};
class branch : public node {
    list<node> children;
public:
    branch(tree *_owner, node *_parent) : node(_owner, _parent) {}
    ...
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top