Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. public bool IsRoot => Parent == null;
  2.  
  3. public int Count => Children.Count;
  4.  
  5. public void AddChild(Node node)
  6. {
  7. node = node ?? throw new ArgumentNullException(nameof(node));
  8. if (IsAncestorOrSelf(node)) // <- you should implement such method
  9. throw new ArgumentException("The node can not be an ancestor or self");
  10. if (IsDescendant(node)) // <- you should implement such method
  11. throw new ArgumentException("The node can not be a descendant");
  12. node.Parent = this;
  13. Children.Add(node);
  14. }
  15.  
  16. public IEnumerable<Node> GetChildren()
  17. {
  18. return Children.ToArray();
  19. }
  20.  
  21. public IEnumerable<Node> GetDescendants()
  22. {
  23. foreach (var child in Children)
  24. {
  25. yield return child;
  26. foreach (var descendant in child.GetDescendants())
  27. {
  28. yield return descendant;
  29. }
  30. }
  31. }
  32.  
  33. public Node DeepCopy()
  34. {
  35. var other = (Node)MemberwiseClone();
  36.  
  37. other.Children = new List<Node>(collection: Children);
  38. other.Parent = Parent?.DeepCopy();
  39. other.Value = new Node(value: Value);
  40.  
  41. return other;
  42. }
  43.  
  44. public void RemoveChild(Node node)
  45. {
  46. if (node != this && Children.Contains(node))
  47. {
  48. Children.Remove(node);
  49. }
  50. }
  51.  
  52. public class Node<T>
  53. {
  54. public T Value { get; }
  55. ...
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement