Swap Nodes in Binary tree of every k 'th level | c ++ program swap nodes ; A Binary Tree Node ; function to create a new tree node ; swap two Node ; A utility function swap left - node & right node of tree of every k 'th level ; base case ; if current level + 1 is present in swap vector then we swap left & right node ; Recur for left and right subtrees ; This function mainly calls recursive function swapEveryKLevelUtil ( ) ; call swapEveryKLevelUtil function with initial level as 1. ; Utility method for inorder tree traversal ; Driver Code ; 1 / \ 2 3 / / \ 4 7 8
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } void Swap ( Node * * a , Node * * b ) { Node * temp = * a ; * a = * b ; * b = temp ; } void swapEveryKLevelUtil ( Node * root , int level , int k ) { if ( root == NULL || ( root -> left == NULL && root -> right == NULL ) ) return ; if ( ( level + 1 ) % k == 0 ) Swap ( & root -> left , & root -> right ) ; swapEveryKLevelUtil ( root -> left , level + 1 , k ) ; swapEveryKLevelUtil ( root -> right , level + 1 , k ) ; } void swapEveryKLevel ( Node * root , int k ) { swapEveryKLevelUtil ( root , 1 , k ) ; } void inorder ( Node * root ) { if ( root == NULL ) return ; inorder ( root -> left ) ; cout << root -> data << " ▁ " ; inorder ( root -> right ) ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> right -> right = newNode ( 8 ) ; root -> right -> left = newNode ( 7 ) ; int k = 2 ; cout << " Before ▁ swap ▁ node ▁ : " << endl ; inorder ( root ) ; swapEveryKLevel ( root , k ) ; cout << " After swap Node : " << endl ; inorder ( root ) ; return 0 ; }