Sayonara Player
Tree.h
1 
2 /* Copyright (C) 2011-2020 Michael Lugmair (Lucio Carreras)
3  *
4  * This file is part of sayonara player
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10 
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15 
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #ifndef TREE_H
21 #define TREE_H
22 
23 #include <QList>
24 #include <algorithm>
25 
26 namespace Util
27 {
28  template<typename T>
33  class Tree
34  {
35  public:
36  Tree* parent = nullptr;
37  T data;
38  QList<Tree*> children;
39 
40  Tree() :
41  Tree(T {}) {}
42 
43  explicit Tree(const T& data) :
44  parent(nullptr),
45  data(data) {}
46 
47  ~Tree()
48  {
49  for(auto* child : children)
50  {
51  delete child;
52  child = nullptr;
53  }
54 
55  children.clear();
56  data = T();
57  }
58 
64  Tree* addChild(Tree* node)
65  {
66  node->parent = this;
67 
68  this->children << node;
69  this->sort(false);
70 
71  return node;
72  }
73 
74  Tree* addChild(const T& data)
75  {
76  auto* node = new Tree(data);
77  return addChild(node);
78  }
79 
85  Tree* removeChild(Tree* deletedNode)
86  {
87  auto it = std::find_if(children.begin(), children.end(), [&](const auto* node){
88  return (node == deletedNode);
89  });
90 
91  if(it != children.end()) {
92  auto* node = *it;
93  children.erase(it);
94  node->parent = nullptr;
95  return node;
96  }
97 
98  return nullptr;
99  }
100 
105  void sort(bool recursive)
106  {
107  if(children.isEmpty()) {
108  return;
109  }
110 
111  auto lambda = [](auto* tree1, auto* tree2) {
112  return (tree1->data < tree2->data);
113  };
114 
115  std::sort(children.begin(), children.end(), lambda);
116 
117  if(recursive)
118  {
119  for(auto* child : children)
120  {
121  child->sort(recursive);
122  }
123  }
124  }
125  };
126 }
127 
128 #endif // TREE_H
Util::Tree::removeChild
Tree * removeChild(Tree *deletedNode)
remove a node from the current node
Definition: Tree.h:85
Util::Tree::addChild
Tree * addChild(Tree *node)
adds a child to the given node
Definition: Tree.h:64
QList
Definition: EngineUtils.h:33
Util
Helper functions.
Definition: GenreView.h:36
Util::Tree
The Tree class.
Definition: Tree.h:34
Util::Tree::sort
void sort(bool recursive)
sort children of all nodes in ascending way according to their data
Definition: Tree.h:105