Guest User

Untitled

a guest
Dec 14th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. template <typename T>
  5. class Tree
  6. {
  7. public:
  8. struct Node
  9. {
  10. T data;
  11. std::vector<Node*> children;
  12.  
  13. Node(const T& value) : data(value) {}
  14. };
  15.  
  16. public:
  17. //ima dinamichna pamet => 4ka
  18. Tree() : root(nullptr) {}
  19. Tree(const Tree<T>& copy)
  20. {
  21. copy(this->root, copy.root);
  22. }
  23. Tree<T>& operator=(const Tree<T>& obj)
  24. {
  25. if (this != &obj)
  26. {
  27. deleteTree(this->root);
  28. copy(this->root, obj.root);
  29. }
  30. return *this;
  31. }
  32. ~Tree()
  33. {
  34. deleteTree(this->root);
  35. }
  36. void setRoot(const T& value)
  37. {
  38. if (!this->root)
  39. {
  40. this->root = new Node(value);
  41. }
  42. else
  43. this->root->data = value;
  44. }
  45. void insertChild(const Tree<T> & child)
  46. {
  47. if (!child.root) return;
  48. Node* toChild = nullptr;
  49. copy(toChild, child.root);
  50. this->root->children.push_back(toChild);
  51. }
  52.  
  53. void insert(const unsigned* route, size_t length, const T& elem)
  54. {
  55. insert(this->root, route, length, elem);
  56. }
  57. void insert(Node*& node, const unsigned* route, size_t length, const T& elem)
  58. {
  59. if (!node && length == 0)
  60. {
  61. node = new Node(elem);
  62. return;
  63. }
  64. if (length == 0)
  65. {
  66. Node* newElem = new Node(elem);
  67. node->children.push_back(newElem);
  68. return;
  69. }
  70. if (route[0] < this->node->children.size())
  71. {
  72. insert(node->children[route[0]], route + 1, length - 1, elem);
  73. }
  74.  
  75. }
  76.  
  77. private:
  78. Node* root;
  79. void copy(Node*& to, const Node* from)
  80. {
  81. if (from == nullptr) { to = nullptr; return; }
  82.  
  83. to = new Node(from->data); //zaradi tva imame node*& to kato parametur za tva se slaga &
  84.  
  85. for (const Node* child : from->children)
  86. {
  87. Node* toChild = nullptr;
  88. copy(toChild, child);
  89.  
  90. to->children.push_back(toChild);
  91. }
  92. }
  93. void deleteTree(Node*& node)
  94. {
  95. if (node == nullptr) return;
  96.  
  97. for (Node* child : node->children)
  98. {
  99. deleteTree(child);
  100. }
  101. delete node;
  102. node = nullptr;
  103. }
  104. };
  105.  
  106.  
  107. int main()
  108. {
  109. Tree<int> myTree;
  110.  
  111.  
  112.  
  113.  
  114.  
  115.  
  116. return 0;
  117. }
Add Comment
Please, Sign In to add comment