Guest User

Untitled

a guest
Apr 24th, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. class Node:
  2. def __init__(self, val):
  3. self.val = val
  4. self.left = None
  5. self.right = None
  6.  
  7. def insert(self, x):
  8. if x < self.val:
  9. if self.left == None:
  10. self.left = Node(x)
  11. else:
  12. self.left.insert(x)
  13. elif x > self.val:
  14. if self.right == None:
  15. self.right = Node(x)
  16. else:
  17. self.right.insert(x)
  18.  
  19. def has(self, x):
  20. if x < self.val and self.left != None:
  21. return self.left.has(x)
  22. elif x > self.val and self.right != None:
  23. return self.right.has(x)
  24. if self.val == x:
  25. return True
  26. else:
  27. return False
  28.  
  29.  
  30.  
  31. def find_CA(root,a,b): #finds Common Ancestor
  32. if root.val > a and root.val > b:
  33. return find_CA(root.left,a,b)
  34. elif root.val < a and root.val < b:
  35. return find_CA(root.right,a,b)
  36. return root
  37.  
  38.  
  39. def distance_to(root, x):
  40. if root.val == x:
  41. return 0
  42. elif root.val > x:
  43. return 1 + distance_to(root.left, x)
  44. return 1 + distance_to(root.right, x)
  45.  
  46.  
  47. def total_distance(root, a, b):
  48. if root.has(a) and root.has(b):
  49. root = find_CA(root, a, b)
  50. return distance_to(root, a) + distance_to(root, b)
  51. else:
  52. if not root.has(a):
  53. return ("Tree does not contains node " + str(a))
  54. elif not root.has(b):
  55. return ("Tree does not contains node " + str(b))
  56.  
  57. ##test##
  58. #creates tree
  59. tree = Node(8)
  60. for i in [3,10,1,6,14,7,13]:
  61. tree.insert(i)
  62.  
  63. # 8
  64. # / \
  65. # 3 10
  66. # / \ \
  67. # 1 6 14
  68. # \ /
  69. # 7 13
  70. #
  71.  
  72. print(total_distance(tree, 13, 7))
  73. print(total_distance(tree, 7, 13))
  74. print(total_distance(tree, 1, 7))
  75. print(total_distance(tree, 10, 13))
  76. print(total_distance(tree, 6, 13))
  77. print(total_distance(tree, -6, 13))
  78. for i in range(15):
  79.  
  80. print(i, tree.has(i))
  81. ###
Add Comment
Please, Sign In to add comment