Guest User

Untitled

a guest
Apr 24th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 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. def find_CA(root, a, b): #finds Common Ancestor
  30.  
  31. if root.val > a and root.val > b:
  32. return find_CA(root.left, a, b)
  33. elif root.val < a and root.val < b:
  34. return find_CA(root.right, a, b)
  35. return root
  36.  
  37. def shortest_path(root, a, b):
  38. ca = find_CA(root, a, b)
  39. return path(ca, a, b)
  40.  
  41. def path(ca, a, b):
  42. p = []
  43. ca_to_leaf(ca, a, p)
  44. p.reverse()
  45. p.pop() #to avoid repeated common ancestor on p
  46. ca_to_leaf(ca, b, p)
  47. return p
  48.  
  49. def ca_to_leaf(ca, end, p):
  50. if ca.val == end:
  51. p.append(end)
  52.  
  53. else:
  54. p.append(ca.val)
  55. if end < ca.val:
  56. ca_to_leaf(ca.left, end, p)
  57. else:
  58. ca_to_leaf(ca.right, end, p)
  59.  
  60. ##test##
  61. #creates tree
  62. x = Node(8)
  63. for i in [3,10,1,6,14,7,13]:
  64. x.insert(i)
  65.  
  66. # 8
  67. # / \
  68. # 3 10
  69. # / \ \
  70. # 1 6 14
  71. # \ /
  72. # 7 13
  73. #
  74.  
  75. print(shortest_path(x, 13, 7))
  76. print(shortest_path(x, 7, 13))
  77. print(shortest_path(x, 1, 7))
Add Comment
Please, Sign In to add comment