m2skills

cousin python

Jun 13th, 2018
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. # http://code2begin.blogspot.com
  2. # program to print if 2 nodes of a binary tree are cousins or not
  3.  
  4. # node class
  5. class node:
  6.     def __init__(self, element):
  7.         self.data = element
  8.         self.left = None
  9.         self.right = None
  10.  
  11.  
  12. # function to find and return the level of a node in binary tree
  13. def level_of_node(root, data, level=-1):
  14.     # if the tree is empty or if we reach a leaf node then return 0
  15.     if root is None:
  16.         return -1
  17.     if root.data == data:
  18.         return level + 1
  19.  
  20.     # check in the left subtree for the element
  21.     # if found then return the level
  22.     level_node = level_of_node(root.left, data, level + 1)
  23.     if level_node != -1:
  24.         return level_node
  25.  
  26.     # searching for the node in right subtree
  27.     level_node = level_of_node(root.right, data, level + 1)
  28.     return level_node
  29.  
  30.  
  31.  
  32. # function to check if 2 nodes are siblings or not
  33. def isSibling(parent, n1, n2):
  34.     if parent is None:
  35.         return False
  36.  
  37.     if parent.left is not None and parent.right is not None:
  38.         return (parent.left.data == n1 and parent.right.data == n2) or (parent.left.data == n2 and parent.right.data == n1)
  39.  
  40.     return isSibling(parent.left, n1, n2) or isSibling(parent.right, n1, n2)
  41.  
  42.  
  43. def isCousin(root, a, b):
  44.     if (level_of_node(root, a) == level_of_node(root, b)) and isSibling(root, a, b):
  45.         return True
  46.     return False
  47.  
  48.  
  49. head = node(1)
  50. head.left = node(2)
  51. head.right = node(3)
  52. head.left.left = node(4)
  53. head.left.right = node(5)
  54. head.right.right = node(6)
  55. head.left.left.right = node(7)
  56. head.right.right.left = node(8)
  57. head.left.left.right.left = node(9)
  58. head.left.left.right.left.left = node(10)
  59. head.right.right.left.right = node(11)
  60. print("Nodes 2 and 3 are siblings : " + str(isCousin(head, 2, 3)))
  61. print("Nodes 6 and 10 are siblings : " + str(isCousin(head, 6, 10)))
  62. print("Nodes 7 and 8 are siblings : " + str(isCousin(head, 7, 8)))
Add Comment
Please, Sign In to add comment