m2skills

distance BT python

Jun 3rd, 2018
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.96 KB | None | 0 0
  1. # http://code2begin.blogspot.compile
  2. # Program to find distance between 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. # function to find and return the level of a node in binary tree
  12. def level_of_node(root, data, level=-1):
  13.     # if the tree is empty or if we reach a leaf node then return 0
  14.     if root is None:
  15.         return -1
  16.     if root.data == data:
  17.         return level + 1
  18.  
  19.     # check in the left subtree for the element
  20.     # if found then return the level
  21.     level_node = level_of_node(root.left, data, level + 1)
  22.     if level_node != -1:
  23.         return level_node
  24.  
  25.     # searching for the node in right subtree
  26.     level_node = level_of_node(root.right, data, level + 1)
  27.     return level_node
  28.  
  29.  
  30. def least_common_ancestor(root, n1, n2):
  31.     if root is None:
  32.         return root
  33.  
  34.     if root.data == n1 or root.data == n2:
  35.         return root
  36.  
  37.     left = least_common_ancestor(root.left, n1, n2)
  38.     right = least_common_ancestor(root.right, n1, n2)
  39.  
  40.     if left is not None and right is not None:
  41.         return root
  42.  
  43.     if left is not None:
  44.         return least_common_ancestor(root.left, n1, n2)
  45.  
  46.     return least_common_ancestor(root.right, n1, n2)
  47.  
  48.  
  49. # function that returns the distance between 2 given nodes
  50. def distance_between(root, a, b):
  51.     LCA = least_common_ancestor(root, a, b)
  52.     return level_of_node(LCA, a) + level_of_node(LCA, b)
  53.  
  54.  
  55.  
  56. head = node(1)
  57. head.left = node(2)
  58. head.right = node(3)
  59. head.left.left = node(4)
  60. head.left.right = node(5)
  61. head.right.right = node(6)
  62. head.left.left.right = node(7)
  63. head.right.right.left = node(8)
  64. head.left.left.right.left = node(9)
  65. head.left.left.right.left.left = node(10)
  66. head.right.right.left.right = node(11)
  67. print("Distance between nodes 6 and 10 is : " + str(distance_between(head, 6, 10)))
  68. print("Distance between nodes 1 and 10 is : " + str(distance_between(head, 1, 10)))
  69. print("Distance between nodes 11 and 10 is : " + str(distance_between(head, 11, 10)))
Add Comment
Please, Sign In to add comment