Advertisement
POdkovyrkinDaniil

Untitled

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