Бинарное дерево Tree<T>
Вашему вниманию предлагается класс, незаменимый при работе с древовидными данными.
Класс реализует все потребности при работе с бинарными деревьями: добавление, хранение, удаление, энумерацию.
Пока страдает описание, но, думаю, это я исправлю в ближайшее время, хотя, для сведущих, полагаю, не составит труда разобраться что к чему.
Что в нашем деле редко, так это — широкая поддержка наследования: поле version является protected (в отличие от System.Collections.Generic.List<T>), также доступны виртуальные методы и события.
C#: | Select code |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 | using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; namespace UsingsRU.Patterns { /// <summary> /// Класс, предназначенный для хранения данных в виде дерева /// с произвольным числом ветвлений в каждом узле. /// </summary> /// <typeparam name="T">Тип данных.</typeparam> public class Tree<T> : ICloneable, IEnumerable<Tree<T>>, IEnumerable<T> { #region Nested classes public class TreeItemActionEventArgs : EventArgs { public readonly Tree<T> TreeItem; public TreeItemActionEventArgs(Tree<T> treeItem) { TreeItem = treeItem; } } public class TreeItemsActionEventArgs : EventArgs { public readonly IEnumerable<Tree<T>> TreeItems; public TreeItemsActionEventArgs(IEnumerable<Tree<T>> treeItems) { TreeItems = treeItems; } } public class TreeItemBeforeActionEventArgs : TreeItemActionEventArgs { public bool Cancel; public TreeItemBeforeActionEventArgs(Tree<T> treeItem) : base(treeItem) { } } public class TreeItemsBeforeActionEventArgs : TreeItemsActionEventArgs { public bool Cancel; public TreeItemsBeforeActionEventArgs(List<Tree<T>> treeItem) : base(treeItem) { } } #endregion public Tree<T> Parent { get; private set; } public T Value; private readonly List<Tree<T>> localChildren; protected int version; public Tree() : this(default(T)) { } /// <summary> /// Создать корневой узел (Root). /// </summary> /// <param name="value">Значение узла.</param> public Tree(T value) : this(null, null, value) { } /// <summary> /// Создать корневой узел (Root) и установить список дочерних узлов <c>children</c>. /// </summary> /// <param name="children">Список дочерних узлов.</param> /// <param name="value">Значение узла.</param> public Tree(List<Tree<T>> children, T value) : this(null, children, value) { } /// <summary> /// Создать узел, являющийся потомком узла <c>parent</c>, и установить список дочерних узлов <c>children</c>. /// </summary> /// <param name="parent">Родительский узел.</param> /// <param name="children">Список дочерних узлов.</param> /// <param name="value">Значение узла.</param> public Tree(Tree<T> parent, List<Tree<T>> children, T value) { localChildren = children ?? new List<Tree<T>>(); Value = value; for (int i = 0; i < localChildren.Count; i++) localChildren[i].Parent = this; if (parent != null) parent.AddChild(this); else Parent = null; } public event EventHandler<TreeItemActionEventArgs> ItemAdded; public event EventHandler<TreeItemsActionEventArgs> ItemsAdded; public event EventHandler<TreeItemActionEventArgs> ItemRemoving; public event EventHandler<TreeItemsActionEventArgs> ItemsRemoving; public void Add(Tree<T> child) { AddChild(child); } protected virtual void AddChild(Tree<T> child) { child.Parent = this; localChildren.Add(child); version++; if (ItemAdded != null) ItemAdded(this, new TreeItemActionEventArgs(child)); } public void AddRange(IEnumerable<Tree<T>> children) { AddChildren(children); } protected virtual void AddChildren(IEnumerable<Tree<T>> children) { foreach (Tree<T> child in children) child.Parent = this; localChildren.AddRange(children); version++; if (ItemsAdded != null) ItemsAdded(this, new TreeItemsActionEventArgs(children)); } public bool Remove(Tree<T> child) { return RemoveChild(child); } public virtual bool RemoveChild(Tree<T> child) { TreeItemBeforeActionEventArgs e = new TreeItemBeforeActionEventArgs(child); if (ItemRemoving != null) { ItemRemoving(this, e); if (e.Cancel) { version++; return false; } } return localChildren.Remove(child); } public void RemoveRange(int index, int count) { RemoveChildren(index, count); } public virtual void RemoveChildren(int index, int count) { TreeItemsBeforeActionEventArgs e = new TreeItemsBeforeActionEventArgs(localChildren.GetRange(index, count)); if (ItemsRemoving != null) { ItemsRemoving(this, e); if (e.Cancel) { version++; return; } } localChildren.RemoveRange(index, count); } public Tree<T> this[int index] { get { return localChildren[index]; } } public ReadOnlyCollection<Tree<T>> Children { get { return localChildren.AsReadOnly(); } } public Tree<T> Root { get { return IsRoot ? this : Parent.Root; } } public bool IsRoot { get { return Parent == null; } } public bool HasChildren { get { return localChildren.Count != 0; } } public int Level { get { return IsRoot ? 0 : Parent.Level + 1; } } public int Length { get { int i = 0; ForEach(a => i++); return i; } } public List<Tree<T>> Parents { get { var list = new List<Tree<T>>(Level); var current = this; while (current.Parent != null) { list.Add(Parent); current = current.Parent; } return list; } } public bool IsChildOf(Tree<T> node) { var current = this; while (current.Parent != null) { if (current.Parent == node) return true; current = current.Parent; } return false; } public bool IsParentOf(Tree<T> node) { return HasChildren && node.IsChildOf(this); } public void ForEach(Action<Tree<T>> action) { action(this); for (int i = 0; i < localChildren.Count; i++) localChildren[i].ForEach(action); } public void ForEach<S>(Action<Tree<T>> action) where S : T { if (Value is S) action(this); for (int i = 0; i < localChildren.Count; i++) if (localChildren[i].Value is S) localChildren[i].ForEach(action); } public Tree<T> Find(Predicate<Tree<T>> match) { if (match(this)) return this; for (int i = 0; i < localChildren.Count; i++) { Tree<T> node = localChildren[i].Find(match); if (node != null) return node; } return null; } public Tree<T> Find(T value) { return Find(typeof(IEquatable<T>).IsAssignableFrom(typeof(T)) ? (Predicate<Tree<T>>) (node => (((IEquatable<T>) node.Value).Equals(value))) : node => (ReferenceEquals(node.Value, value))); } public List<Tree<T>> FindAll(Predicate<Tree<T>> match) { List<Tree<T>> items = new List<Tree<T>>(); if (match(this)) items.Add(this); for (int i = 0; i < localChildren.Count; i++) items.AddRange(localChildren[i].FindAll(match)); return items; } public List<T> FindAll(Predicate<T> match) { List<T> items = new List<T>(); if (match(Value)) items.Add(Value); for (int i = 0; i < localChildren.Count; i++) items.AddRange(localChildren[i].FindAll(match)); return items; } public List<S> FindAll<S>() where S : T { List<S> items = new List<S>(); if (Value is S) items.Add((S)Value); for (int i = 0; i < localChildren.Count; i++) items.AddRange(localChildren[i].FindAll<S>()); return items; } #region ICloneable Members public object Clone() { return CloneTree(); } #endregion public Tree<T> CloneTree() { return new Tree<T>(Parent, new List<Tree<T>>(localChildren), Value); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { yield return Value; for (int i = 0; i < localChildren.Count; i++) ((IEnumerable<T>)localChildren[i]).GetEnumerator(); } public IEnumerator<Tree<T>> GetEnumerator() { yield return this; for (int i = 0; i < localChildren.Count; i++) localChildren[i].GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } |
Удачи!
Обсуждение на форуме: http://usings.ru/forum/viewtopic.php?t=7
3 ответов Оставить комментарий
разбираю ваш код.
и возник вопрос. насколько я понимаю, бинарные деревья — это структуры, в каждом узле которых есть ссылки на левую и правую ветвь, т.е. в каждом узле есть только два «потомка» — левый и правый. по вашему коду получается, что при узел может содержать сколько угодно много непосредственных «потомков».
Tree T = new Tree(10);
T.Add(new Tree(5));
T.Add(new Tree(3));
T.Add(new Tree(2));
По приведенному коду выходит, что у дерева T в поле Children лежат три узла. выходит, что дерево не бинарное. или я неправильно что-то понимаю?
Да, Вы правы. На первый взгляд такое дерево — не бинарное. Однако, если мысленно представить коллекцию children в несколько ином виде (например LinkedList) — получится как раз бинарное дерево. По сути, любое дерево без пересечений может быть представлено в виде бинарного (Подробнее: в бинарных деревьях, действительно, у каждого узла есть ссылки на 2 элемента: Sibling и Child. Где Sibling — следующий узел того же уровня, а Child — первый потомок узла. Утверждение, что у каждого узла может быть 2 потомка — без этого уточнения считаю некорректным). Так что можно считать, что так и есть, только поле children служит для предоставления удобного доступа к потомкам узла.
Надеюсь, я не очень сумбурно объяснил.
Здравствуйте! Не могли бы закинуть ещё и вывод в консоль всего вашего дерева?:) и объяснить чутка как использовать данный класс! Было бы здорово!
ps
код очень красив, мне очень нравится!