Swap Nodes in Binary tree of every k 'th level | constructor to create a new node ; A utility function swap left node and right node of tree of every k 'th level  ; Base Case ; If current level + 1 is present in swap vector then we swap left and right node ; Recur for left and right subtree ; This function mainly calls recursive function swapEveryKLevelUtil ; Call swapEveryKLevelUtil function with initial level as 1 ; Method to find the inorder tree travesal ; 1 / \ 2 3 / / \ 4 7 8
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 swapEveryKLevelUtil ( root , level , k ) : NEW_LINE INDENT if ( root is None or ( root . left is None and root . right is None ) ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( level + 1 ) % k == 0 : NEW_LINE INDENT root . left , root . right = root . right , root . left NEW_LINE DEDENT swapEveryKLevelUtil ( root . left , level + 1 , k ) NEW_LINE swapEveryKLevelUtil ( root . right , level + 1 , k ) NEW_LINE DEDENT def swapEveryKLevel ( root , k ) : NEW_LINE INDENT swapEveryKLevelUtil ( root , 1 , k ) NEW_LINE DEDENT def inorder ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT inorder ( root . left ) NEW_LINE print root . data , NEW_LINE inorder ( root . right ) NEW_LINE 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 . right . right = Node ( 8 ) NEW_LINE root . right . left = Node ( 7 ) NEW_LINE k = 2 NEW_LINE print " Before ▁ swap ▁ node ▁ : " NEW_LINE inorder ( root ) NEW_LINE swapEveryKLevel ( root , k ) NEW_LINE print   " NEW_LINE After swap Node :   " NEW_LINE inorder ( root ) NEW_LINE