Advertisement
LevMukoseev

Untitled

Apr 24th, 2019
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.87 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4.  
  5. namespace BinaryTrees
  6. {
  7. public class BinaryTree<T> : IEnumerable<T>
  8. where T : IComparable
  9.  
  10. {
  11. private Node root;
  12.  
  13. public int Count
  14. {
  15. get;
  16. private set;
  17. }
  18.  
  19. public class Node
  20. {
  21. public Node Left;
  22. public Node Right;
  23. public T Value;
  24. }
  25.  
  26. public BinaryTree()
  27. {
  28. root = new Node();
  29. }
  30.  
  31. public void Add(T value)
  32. {
  33. var current = root;
  34.  
  35. while (true)
  36. {
  37. if (Count == 0)
  38. {
  39. current.Value = value;
  40. Count++;
  41. break;
  42. }
  43.  
  44. if (value.CompareTo(current.Value) <= 0)
  45. {
  46. if (current.Left == null)
  47. {
  48. current.Left = new Node { Value = value };
  49. Count++;
  50. break;
  51. }
  52. else
  53. current = current.Left;
  54. }
  55.  
  56. else
  57. {
  58. if (current.Right == null)
  59. {
  60. current.Right = new Node { Value = value };
  61. Count++;
  62. break;
  63. }
  64. else
  65. current = current.Right;
  66. }
  67. }
  68. }
  69.  
  70. public bool Contains(T key)
  71. {
  72. var current = root;
  73. while (true)
  74. {
  75. if (Count == 0)
  76. return false;
  77.  
  78. if (current == null)
  79. return false;
  80.  
  81. var compare = key.CompareTo(current.Value);
  82.  
  83. if (compare == 0)
  84. return true;
  85.  
  86. current = compare < 0
  87. ? current.Left
  88. : current.Right;
  89. }
  90. }
  91.  
  92. public IEnumerator<T> GetEnumerator()
  93. {
  94. var stack = new Stack<Node>();
  95.  
  96. var current = root;
  97.  
  98. while (true)
  99. {
  100. if (current != null)
  101. {
  102. stack.Push(current);
  103. current = current.Left;
  104. }
  105.  
  106. else if (stack.Count != 0)
  107. {
  108. current = stack.Pop();
  109. yield return current.Value;
  110. current = current.Right;
  111. }
  112.  
  113. else
  114. break;
  115. }
  116. }
  117.  
  118. IEnumerator IEnumerable.GetEnumerator()
  119. {
  120. return GetEnumerator();
  121. }
  122. }
  123. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement