Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # http://code2begin.blogspot.com
- # Program to find the least common ancestor of 2 nodes in a given binary tree
- # node class
- class node:
- def __init__(self, element):
- self.data = element
- self.left = None
- self.right = None
- 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)
- 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("Least common Ancestor of nodes 6 and 10 is : " + str(least_common_ancestor(head, 6, 10).data))
- print("Least common Ancestor of nodes 4 and 5 is : " + str(least_common_ancestor(head, 4, 5).data))
- print("Least common Ancestor of nodes 5 and 10 is : " + str(least_common_ancestor(head, 5, 10).data))
Add Comment
Please, Sign In to add comment