m2skills

LCA python

Jun 3rd, 2018
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. # http://code2begin.blogspot.com
  2. # Program to find the least common ancestor of 2 nodes in a given binary tree
  3. # node class
  4. class node:
  5.     def __init__(self, element):
  6.         self.data = element
  7.         self.left = None
  8.         self.right = None
  9.  
  10.  
  11.  
  12. def least_common_ancestor(root, n1, n2):
  13.     if root is None:
  14.         return root
  15.  
  16.     if root.data == n1 or root.data == n2:
  17.         return root
  18.  
  19.     left = least_common_ancestor(root.left, n1, n2)
  20.     right = least_common_ancestor(root.right, n1, n2)
  21.  
  22.     if left is not None and right is not None:
  23.         return root
  24.  
  25.     if left is not None:
  26.         return least_common_ancestor(root.left, n1, n2)
  27.  
  28.     return least_common_ancestor(root.right, n1, n2)
  29.  
  30.  
  31. head = node(1)
  32. head.left = node(2)
  33. head.right = node(3)
  34. head.left.left = node(4)
  35. head.left.right = node(5)
  36. head.right.right = node(6)
  37. head.left.left.right = node(7)
  38. head.right.right.left = node(8)
  39. head.left.left.right.left = node(9)
  40. head.left.left.right.left.left = node(10)
  41. head.right.right.left.right = node(11)
  42.  
  43. print("Least common Ancestor of nodes 6 and 10 is : " + str(least_common_ancestor(head, 6, 10).data))
  44. print("Least common Ancestor of nodes 4 and 5 is : " + str(least_common_ancestor(head, 4, 5).data))
  45. 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