Check if two nodes are cousins in a Binary Tree | A Binary Tree Node ; Recursive function to check if two Nodes are siblings ; Base Case ; Recursive function to find level of Node ' ptr ' in a binary tree ; Base Case ; Return level if Node is present in left subtree ; Else search in right subtree ; Returns 1 if a and b are cousins , otherwise 0 ; 1. The two nodes should be on the same level in the binary tree The two nodes should not be siblings ( means that they should not have the smae parent node ; Driver program to test above function
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def isSibling ( root , a , b ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( ( root . left == a and root . right == b ) or ( root . left == b and root . right == a ) or isSibling ( root . left , a , b ) or isSibling ( root . right , a , b ) ) NEW_LINE DEDENT def level ( root , ptr , lev ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if root == ptr : NEW_LINE INDENT return lev NEW_LINE DEDENT l = level ( root . left , ptr , lev + 1 ) NEW_LINE if l != 0 : NEW_LINE INDENT return l NEW_LINE DEDENT return level ( root . right , ptr , lev + 1 ) NEW_LINE DEDENT def isCousin ( root , a , b ) : NEW_LINE INDENT if ( ( level ( root , a , 1 ) == level ( root , b , 1 ) ) and not ( isSibling ( root , a , b ) ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . left . right . right = Node ( 15 ) NEW_LINE root . right . left = Node ( 6 ) NEW_LINE root . right . right = Node ( 7 ) NEW_LINE root . right . left . right = Node ( 8 ) NEW_LINE node1 = root . left . right NEW_LINE node2 = root . right . right NEW_LINE print " Yes " if isCousin ( root , node1 , node2 ) == 1 else " No " NEW_LINE