Print cousins of a given node in Binary Tree | A utility function to create a new Binary Tree Node ; It returns level of the node if it is present in tree , otherwise returns 0. ; base cases ; If node is present in left subtree ; If node is not present in left subtree ; Prnodes at a given level such that sibling of node is not printed if it exists ; Base cases ; If current node is parent of a node with given level ; Recur for left and right subtrees ; This function prints cousins of a given node ; Get level of given node ; Prnodes of given level . ; Driver Code
class newNode : NEW_LINE INDENT def __init__ ( self , item ) : NEW_LINE INDENT self . data = item NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def getLevel ( root , node , level ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( root == node ) : NEW_LINE INDENT return level NEW_LINE DEDENT downlevel = getLevel ( root . left , node , level + 1 ) NEW_LINE if ( downlevel != 0 ) : NEW_LINE INDENT return downlevel NEW_LINE DEDENT return getLevel ( root . right , node , level + 1 ) NEW_LINE DEDENT def printGivenLevel ( root , node , level ) : NEW_LINE INDENT if ( root == None or level < 2 ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( level == 2 ) : NEW_LINE INDENT if ( root . left == node or root . right == node ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . left ) : NEW_LINE INDENT print ( root . left . data , end = " ▁ " ) NEW_LINE DEDENT if ( root . right ) : NEW_LINE INDENT print ( root . right . data , end = " ▁ " ) NEW_LINE DEDENT DEDENT elif ( level > 2 ) : NEW_LINE INDENT printGivenLevel ( root . left , node , level - 1 ) NEW_LINE printGivenLevel ( root . right , node , level - 1 ) NEW_LINE DEDENT DEDENT def printCousins ( root , node ) : NEW_LINE INDENT level = getLevel ( root , node , 1 ) NEW_LINE printGivenLevel ( root , node , level ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . left . right . right = newNode ( 15 ) NEW_LINE root . right . left = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE root . right . left . right = newNode ( 8 ) NEW_LINE printCousins ( root , root . left . right ) NEW_LINE DEDENT