Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace Generics.BinaryTrees
  9. {
  10. public class BinaryTree<T> : IEnumerable<T> where T : IComparable, new()
  11. {
  12. private BinaryNode<T> Top;
  13.  
  14. public BinaryNode<T> Left => Top.Left;
  15.  
  16. public BinaryNode<T> Right => Top.Right;
  17.  
  18. public T Value => Top.Value;
  19.  
  20. public BinaryTree(T value)
  21. {
  22. Top = new BinaryNode<T>(value);
  23. }
  24.  
  25. public BinaryTree()
  26. {
  27. Top = null;
  28. }
  29.  
  30. private void AddHelper(ref BinaryNode<T> node, T value)
  31. {
  32. if (node == null)
  33. {
  34. var newNode = new BinaryNode<T>(value);
  35. node = newNode;
  36. return;
  37. }
  38. if (value.CompareTo(node.Value) <= 0)
  39. {
  40. AddHelper(ref node.Left, value);
  41. return;
  42. }
  43. if (value.CompareTo(node.Value) > -1)
  44. {
  45. AddHelper(ref node.Right, value);
  46. return;
  47. }
  48.  
  49. }
  50. public void Add(T value)
  51. {
  52. AddHelper(ref Top,value);
  53. }
  54.  
  55. public IEnumerator<T> GetEnumerator()
  56. {
  57. if (Top == null) yield break;
  58.  
  59. var stack = new Stack<BinaryNode<T>>();
  60. var node = Top;
  61.  
  62. while (stack.Count > 0 || node != null)
  63. {
  64. if (node == null)
  65. {
  66. node = stack.Pop();
  67. yield return node.Value;
  68. node = node.Right;
  69. }
  70. else
  71. {
  72. stack.Push(node);
  73. node = node.Left;
  74. }
  75. }
  76. }
  77.  
  78. IEnumerator IEnumerable.GetEnumerator()
  79. {
  80. return GetEnumerator();
  81. }
  82. }
  83.  
  84. public class BinaryNode<T> where T : IComparable
  85. {
  86. public T Value;
  87. public BinaryNode(T value)
  88. {
  89. Value = value;
  90. }
  91.  
  92. public BinaryNode<T> Left;
  93.  
  94. public BinaryNode<T> Right;
  95. }
  96.  
  97. public class BinaryTree
  98. {
  99. public static BinaryTree<T> Create<T>(params T[] items) where T : IComparable, new()
  100. {
  101. var result = new BinaryTree<T>();
  102. foreach (var item in items)
  103. {
  104. result.Add(item);
  105. }
  106.  
  107. return result;
  108. }
  109. }
  110. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement