Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node:
- def __init__(self, val):
- self.val = val
- self.left = None
- self.right = None
- def insert(self, x):
- if x < self.val:
- if self.left == None:
- self.left = Node(x)
- else:
- self.left.insert(x)
- elif x > self.val:
- if self.right == None:
- self.right = Node(x)
- else:
- self.right.insert(x)
- def has(self, x):
- if x < self.val and self.left != None:
- return self.left.has(x)
- elif x > self.val and self.right != None:
- return self.right.has(x)
- if self.val == x:
- return True
- else:
- return False
- def find_CA(root,a,b): #finds Common Ancestor
- if root.val > a and root.val > b:
- return find_CA(root.left,a,b)
- elif root.val < a and root.val < b:
- return find_CA(root.right,a,b)
- return root
- def distance_to(root, x):
- if root.val == x:
- return 0
- elif root.val > x:
- return 1 + distance_to(root.left, x)
- return 1 + distance_to(root.right, x)
- def total_distance(root, a, b):
- if root.has(a) and root.has(b):
- root = find_CA(root, a, b)
- return distance_to(root, a) + distance_to(root, b)
- else:
- if not root.has(a):
- return ("Tree does not contains node " + str(a))
- elif not root.has(b):
- return ("Tree does not contains node " + str(b))
- ##test##
- #creates tree
- tree = Node(8)
- for i in [3,10,1,6,14,7,13]:
- tree.insert(i)
- # 8
- # / \
- # 3 10
- # / \ \
- # 1 6 14
- # \ /
- # 7 13
- #
- print(total_distance(tree, 13, 7))
- print(total_distance(tree, 7, 13))
- print(total_distance(tree, 1, 7))
- print(total_distance(tree, 10, 13))
- print(total_distance(tree, 6, 13))
- print(total_distance(tree, -6, 13))
- for i in range(15):
- print(i, tree.has(i))
- ###
Add Comment
Please, Sign In to add comment