feat: implement Composite
This commit is contained in:
parent
4b82ca17ac
commit
68da0a4b6c
1 changed files with 52 additions and 0 deletions
|
@ -1,8 +1,60 @@
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
class Node {
|
||||||
|
public:
|
||||||
|
virtual ~Node() = default;
|
||||||
|
virtual void print() const = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
class InnerNode : public Node {
|
||||||
|
private:
|
||||||
|
std::string name_;
|
||||||
|
std::vector<Node *> children_;
|
||||||
|
|
||||||
|
public:
|
||||||
|
InnerNode(std::string_view name) : name_(name) {}
|
||||||
|
|
||||||
|
void addNode(Node *node) { children_.push_back(node); }
|
||||||
|
|
||||||
|
void print() const override {
|
||||||
|
std::cout << name_ << " (inner)" << std::endl;
|
||||||
|
|
||||||
|
for (auto child : children_) {
|
||||||
|
child->print();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
class Leaf : public Node {
|
||||||
|
private:
|
||||||
|
std::string name_;
|
||||||
|
|
||||||
|
public:
|
||||||
|
Leaf(std::string_view name) : name_(name) {}
|
||||||
|
|
||||||
|
void print() const override { std::cout << name_ << " (leaf)" << std::endl; }
|
||||||
|
};
|
||||||
|
|
||||||
int main(int argc, char *argv[]) {
|
int main(int argc, char *argv[]) {
|
||||||
|
|
||||||
std::cout << "Composite" << std::endl;
|
std::cout << "Composite" << std::endl;
|
||||||
|
|
||||||
|
InnerNode tree("root");
|
||||||
|
InnerNode left("left"), right("right");
|
||||||
|
Leaf leaf1("leaf 1"), leaf2("leaf 2"), leaf3("leaf 3"), leaf4("leaf 4");
|
||||||
|
|
||||||
|
tree.addNode(&left);
|
||||||
|
tree.addNode(&right);
|
||||||
|
|
||||||
|
left.addNode(&leaf1);
|
||||||
|
left.addNode(&leaf2);
|
||||||
|
|
||||||
|
right.addNode(&leaf3);
|
||||||
|
right.addNode(&leaf4);
|
||||||
|
|
||||||
|
tree.print();
|
||||||
|
|
||||||
return EXIT_SUCCESS;
|
return EXIT_SUCCESS;
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue