Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # http://code2begin.blogspot.compile
- # Program to find distance between 2 nodes in a given binary tree
- # node class
- class node:
- def __init__(self, element):
- self.data = element
- self.left = None
- self.right = None
- # function to find and return the level of a node in binary tree
- def level_of_node(root, data, level=-1):
- # if the tree is empty or if we reach a leaf node then return 0
- if root is None:
- return -1
- if root.data == data:
- return level + 1
- # check in the left subtree for the element
- # if found then return the level
- level_node = level_of_node(root.left, data, level + 1)
- if level_node != -1:
- return level_node
- # searching for the node in right subtree
- level_node = level_of_node(root.right, data, level + 1)
- return level_node
- def least_common_ancestor(root, n1, n2):
- if root is None:
- return root
- if root.data == n1 or root.data == n2:
- return root
- left = least_common_ancestor(root.left, n1, n2)
- right = least_common_ancestor(root.right, n1, n2)
- if left is not None and right is not None:
- return root
- if left is not None:
- return least_common_ancestor(root.left, n1, n2)
- return least_common_ancestor(root.right, n1, n2)
- # function that returns the distance between 2 given nodes
- def distance_between(root, a, b):
- LCA = least_common_ancestor(root, a, b)
- return level_of_node(LCA, a) + level_of_node(LCA, b)
- head = node(1)
- head.left = node(2)
- head.right = node(3)
- head.left.left = node(4)
- head.left.right = node(5)
- head.right.right = node(6)
- head.left.left.right = node(7)
- head.right.right.left = node(8)
- head.left.left.right.left = node(9)
- head.left.left.right.left.left = node(10)
- head.right.right.left.right = node(11)
- print("Distance between nodes 6 and 10 is : " + str(distance_between(head, 6, 10)))
- print("Distance between nodes 1 and 10 is : " + str(distance_between(head, 1, 10)))
- print("Distance between nodes 11 and 10 is : " + str(distance_between(head, 11, 10)))
Add Comment
Please, Sign In to add comment