Guest User

Untitled

a guest
Oct 18th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.13 KB | None | 0 0
  1. public class BinaryTree
  2. {
  3. public BinaryTree()
  4. {
  5. this.Count = 0;
  6. this.Root = null;
  7. }
  8.  
  9. public bool IsEmpty()
  10. {
  11. return this.Root == null;
  12. }
  13.  
  14. public void Insert(int value)
  15. {
  16. if (IsEmpty())
  17. {
  18. this.Root = new Node(value);
  19. }
  20. else
  21. {
  22. this.Root.Insert(Root, value);
  23. }
  24.  
  25. ++Count;
  26. }
  27.  
  28. public Node FindByValue(int value)
  29. {
  30. return this.Root.FindByValue(this.Root, value);
  31. }
  32.  
  33. public bool IsExists(int value)
  34. {
  35. return this.Root.IsExists(this.Root, value);
  36. }
  37.  
  38. public override string ToString()
  39. {
  40. return this.Root.ToString(Root);
  41. }
  42.  
  43. public Node Root { get; set; }
  44. public int Count { get; private set; }
  45. }
  46.  
  47. public class Node
  48. {
  49. public Node(int rootValue)
  50. {
  51. this.Value = rootValue;
  52. }
  53.  
  54. public int Value { get; set; }
  55.  
  56. public Node Left { get; set; }
  57. public Node Right { get; set; }
  58.  
  59. public void Insert(Node rootNode, int value)
  60. {
  61. if (value < rootNode.Value)
  62. {
  63. if (rootNode.Left == null)
  64. {
  65. rootNode.Left = new Node(value);
  66. }
  67. else
  68. {
  69. Insert(this.Left, value);
  70. }
  71. }
  72. else if (value > Value)
  73. {
  74. if (rootNode.Right == null)
  75. {
  76. rootNode.Right = new Node(value);
  77. }
  78. else
  79. {
  80. Insert(this.Right, value);
  81. }
  82. }
  83.  
  84. }
  85.  
  86. public bool IsExists(Node rootNode, int value)
  87. {
  88. return FindByValue(rootNode, value) != null;
  89. }
  90.  
  91. public bool IsLeaf()
  92. {
  93. return (this.Left == null) && (this.Right == null);
  94. }
  95.  
  96. public Node FindByValue(Node rootNode, int value)
  97. {
  98. if (rootNode == null) return null;
  99. if (rootNode.Value == value) return rootNode;
  100.  
  101. if (value < rootNode.Value)
  102. {
  103. return FindByValue(rootNode.Left, value);
  104. }
  105.  
  106. if (value > rootNode.Value)
  107. {
  108. return FindByValue(rootNode.Right, value);
  109. }
  110.  
  111. return null;
  112. }
  113.  
  114. public string ToString(Node rootNode)
  115. {
  116. if (rootNode == null) return string.Empty;
  117.  
  118. return ToString(rootNode.Left) + " " + rootNode.Value + ToString(rootNode.Right);
  119. }
  120. }
Add Comment
Please, Sign In to add comment