Advertisement
Guest User

Untitled

a guest
Apr 24th, 2018
487
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. using System;
  2. namespace BinaryTrees
  3. {
  4. public class TreeNode<T>
  5. {
  6. public TreeNode<T> Left { get; set; }
  7. public TreeNode<T> Right { get; set; }
  8. public T Key { get; private set; }
  9.  
  10. public TreeNode(T key)
  11. {
  12. Key = key;
  13. }
  14. }
  15.  
  16. public class BinaryTree<T>
  17. where T : IComparable
  18. {
  19. public TreeNode<T> Root;
  20. public void Add(TreeNode<T> root, T key)
  21. {
  22. while (true)
  23. {
  24. if (root.Key.CompareTo(key) <= 0)
  25. {
  26. if (root.Right == null)
  27. {
  28. root.Right = new TreeNode<T>(key);
  29. break;
  30. }
  31. root = root.Right;
  32. }
  33. else
  34. {
  35. if (root.Left == null)
  36. {
  37. root.Left = new TreeNode<T>(key);
  38. break;
  39. }
  40. root = root.Left;
  41. }
  42. }
  43. }
  44.  
  45. public void Add(T key)
  46. {
  47. if (Root == null)
  48. {
  49. Root = new TreeNode<T>(key);
  50. }
  51. else
  52. {
  53. Add(Root, key);
  54. }
  55. }
  56.  
  57. public bool Contains(T key)
  58. {
  59. TreeNode<T> previusRoot = null;
  60. var currentRoot = Root;
  61. while (currentRoot != null)
  62. {
  63. if (currentRoot.Key.CompareTo(key) == 0)
  64. {
  65. break;
  66. }
  67. if (currentRoot.Key.CompareTo(key) <= 0)
  68. {
  69. previusRoot = currentRoot;
  70. currentRoot = currentRoot.Right;
  71. }
  72. else
  73. {
  74. previusRoot = currentRoot;
  75. currentRoot = currentRoot.Left;
  76. }
  77. }
  78. return currentRoot != null;
  79. }
  80. }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement