Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # http://code2begin.blogspot.com
- # program to print if 2 nodes of a binary tree are cousins or not
- # 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
- # function to check if 2 nodes are siblings or not
- def isSibling(parent, n1, n2):
- if parent is None:
- return False
- if parent.left is not None and parent.right is not None:
- return (parent.left.data == n1 and parent.right.data == n2) or (parent.left.data == n2 and parent.right.data == n1)
- return isSibling(parent.left, n1, n2) or isSibling(parent.right, n1, n2)
- def isCousin(root, a, b):
- if (level_of_node(root, a) == level_of_node(root, b)) and isSibling(root, a, b):
- return True
- return False
- 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("Nodes 2 and 3 are siblings : " + str(isCousin(head, 2, 3)))
- print("Nodes 6 and 10 are siblings : " + str(isCousin(head, 6, 10)))
- print("Nodes 7 and 8 are siblings : " + str(isCousin(head, 7, 8)))
Add Comment
Please, Sign In to add comment