# Swap Nodes in Binary tree of every k’th level

• Difficulty Level : Easy
• Last Updated : 10 Mar, 2023

Given a binary tree and integer value k, the task is to swap sibling nodes of every k’th level where k >= 1.

Examples:

```Input :  k = 2  and Root of below tree
1             Level 1
/   \
2     3          Level 2
/     /   \
4     7     8       Level 3

Output : Root of the following modified tree
1
/   \
3     2
/  \   /
7    8  4
Explanation : We need to swap left and right sibling
every second level. There is only one
even level with nodes to be swapped are
2 and 3.

Input : k = 1 and Root of following tree

1          Level 1
/   \
2     3       Level 2
/  \
4    5           Level 3
Output : Root of the following modified tree
1
/   \
3     2
/  \
5    4
Since k is 1, we need to swap sibling nodes of
all levels.```

A simple solution of this problem is that for each is to find sibling nodes for each multiple of k and swap them.

An efficient solution is to keep track of level number in recursive calls. And for every node being visited, check if level number of its children is a multiple of k. If yes, then swap the two children of the node. Else, recur for left and right children.

Below is the implementation of above idea

## C++

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

## Java

 `// Java program swap nodes``class` `GFG``{` `// A Binary Tree Node``static` `class` `Node``{``    ``int` `data;``    ``Node left, right;``};` `// function to create a new tree node``static` `Node newNode(``int` `data)``{``    ``Node temp = ``new` `Node();``    ``temp.data = data;``    ``temp.left = temp.right = ``null``;``    ``return` `temp;``}`   `// A utility function swap left- node & right node of tree``// of every k'th level``static` `void` `swapEveryKLevelUtil( Node root, ``int` `level, ``int` `k)``{``    ``// base case``    ``if` `(root== ``null` `||``            ``(root.left==``null` `&& root.right==``null``) )``        ``return` `;` `    ``//if current level + 1 is present in swap vector``    ``//then we swap left & right node``    ``if` `( (level + ``1``) % k == ``0``)``        ``{``            ``Node temp=root.left;``            ``root.left=root.right;``            ``root.right=temp;``        ``}` `    ``// Recur for left and right subtrees``    ``swapEveryKLevelUtil(root.left, level+``1``, k);``    ``swapEveryKLevelUtil(root.right, level+``1``, k);``}` `// This function mainly calls recursive function``// swapEveryKLevelUtil()``static` `void` `swapEveryKLevel(Node root, ``int` `k)``{``    ``// call swapEveryKLevelUtil function with``    ``// initial level as 1.``    ``swapEveryKLevelUtil(root, ``1``, k);``}` `// Utility method for inorder tree traversal``static` `void` `inorder(Node root)``{``    ``if` `(root == ``null``)``        ``return``;``    ``inorder(root.left);``    ``System.out.print(root.data + ``" "``);``    ``inorder(root.right);``}` `// Driver Code``public` `static` `void` `main(String args[])``{``    ``/* 1``        ``/ \``    ``2 3``    ``/ / \``    ``4 7 8 */``    ``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``;``    ``System.out.println(``"Before swap node :"``);``    ``inorder(root);` `    ``swapEveryKLevel(root, k);` `    ``System.out.println(``"\nAfter swap Node :"` `);``    ``inorder(root);``}``}` `// This code is contributed by Arnab Kundu`

## Python3

 `# Python program to swap nodes` `# A binary tree node``class` `Node:` `    ``# constructor to create a new node ``    ``def` `__init__(``self``, data):``        ``self``.data ``=` `data``        ``self``.left ``=` `None``        ``self``.right ``=` `None` `# A utility function swap left node and right node of tree``# of every k'th level``def` `swapEveryKLevelUtil(root, level, k):``    ` `    ``# Base Case``    ``if` `(root ``is` `None` `or` `(root.left ``is` `None` `and``                        ``root.right ``is` `None` `) ):``        ``return` `    ``# If current level+1 is present in swap vector``    ``# then we swap left and right node``    ``if` `(level``+``1``)``%``k ``=``=` `0``:``        ``root.left, root.right ``=` `root.right, root.left``    ` `    ``# Recur for left and right subtree``    ``swapEveryKLevelUtil(root.left, level``+``1``, k)``    ``swapEveryKLevelUtil(root.right, level``+``1``, k)` `    ` `# This function mainly calls recursive function``# swapEveryKLevelUtil``def` `swapEveryKLevel(root, k):``    ` `    ``# Call swapEveryKLevelUtil function with``    ``# initial level as 1``    ``swapEveryKLevelUtil(root, ``1``, k)` `# Method to find the inorder tree traversal``def` `inorder(root):``    ` `    ``# Base Case``    ``if` `root ``is` `None``:``        ``return``    ``inorder(root.left)``    ``print``(root.data,end``=``" "``)``    ``inorder(root.right)` `# Driver code``"""``          ``1``        ``/   \``       ``2     3``     ``/      /  \``    ``4      7    8``"""``root ``=` `Node(``1``)``root.left ``=` `Node(``2``)``root.right ``=` `Node(``3``)``root.left.left ``=` `Node(``4``)``root.right.right ``=` `Node(``8``)``root.right.left ``=` `Node(``7``)` `k ``=` `2``print``(``"Before swap node :"``)``inorder(root)` `swapEveryKLevel(root, k)` `print` `(``"\nAfter swap Node : "``)``inorder(root)` `# This code is contributed by Nikhil Kumar Singh(nickzuck_007)`

## C#

 `// C# program swap nodes``using` `System;` `class` `GFG``{` `// A Binary Tree Node``public` `class` `Node``{``    ``public` `int` `data;``    ``public` `Node left, right;``};` `// function to create a new tree node``static` `Node newNode(``int` `data)``{``    ``Node temp = ``new` `Node();``    ``temp.data = data;``    ``temp.left = temp.right = ``null``;``    ``return` `temp;``}`   `// A utility function swap left- node & right node of tree``// of every k'th level``static` `void` `swapEveryKLevelUtil( Node root, ``int` `level, ``int` `k)``{``    ``// base case``    ``if` `(root == ``null` `||``            ``(root.left == ``null` `&& root.right==``null``) )``        ``return` `;` `    ``//if current level + 1 is present in swap vector``    ``//then we swap left & right node``    ``if` `( (level + 1) % k == 0)``        ``{``            ``Node temp=root.left;``            ``root.left=root.right;``            ``root.right=temp;``        ``}` `    ``// Recur for left and right subtrees``    ``swapEveryKLevelUtil(root.left, level+1, k);``    ``swapEveryKLevelUtil(root.right, level+1, k);``}` `// This function mainly calls recursive function``// swapEveryKLevelUtil()``static` `void` `swapEveryKLevel(Node root, ``int` `k)``{``    ``// call swapEveryKLevelUtil function with``    ``// initial level as 1.``    ``swapEveryKLevelUtil(root, 1, k);``}` `// Utility method for inorder tree traversal``static` `void` `inorder(Node root)``{``    ``if` `(root == ``null``)``        ``return``;``    ``inorder(root.left);``    ``Console.Write(root.data + ``" "``);``    ``inorder(root.right);``}` `// Driver Code``public` `static` `void` `Main(String []args)``{``    ``/* 1``        ``/ \``    ``2 3``    ``/ / \``    ``4 7 8 */``    ``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;``    ``Console.WriteLine(``"Before swap node :"``);``    ``inorder(root);` `    ``swapEveryKLevel(root, k);` `    ``Console.WriteLine(``"\nAfter swap Node :"` `);``    ``inorder(root);``}``}` `// This code contributed by Rajput-Ji`

## Javascript

 ``

Output

```Before swap node :
4 2 1 7 3 8
After swap Node :
7 3 8 1 4 2 ```

Time Complexity: O(N) where N is the Number of nodes in a given binary tree.
Auxiliary Space: O(log(N))

This article is contributed by Nishant_singh(pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Another Approach(Iterative):
The given problem can be solved by using the Level Order Traversal(https://www.geeksforgeeks.org/level-order-tree-traversal/). Follow the steps below to solve the problem:

1) Create a queue(q), and store the nodes alongside its level and continuously iterate for next levels.
2) Perform level order traversal and check if (level+1)%k == 0 then swap its left and right children.
3) After completing the above steps, print the inorder traversals of previous and next tree.

Below is the implementation of above approach:

## C++

 `// C++ program for the above approach``#include``using` `namespace` `std;` `// struct of binary tree node``struct` `Node{``    ``int` `data;``    ``Node* left;``    ``Node* right;``};` `// function to create a new node``Node* newNode(``int` `data){``    ``Node* temp = ``new` `Node();``    ``temp->data = data;``    ``temp->left = temp->right = NULL;``    ``return` `temp;``}` `// swap two nodes``void` `Swap(Node**a, Node**b){``    ``Node* temp = *a;``    ``*a = *b;``    ``*b = temp;``}` `// a utility function swap left-node and right node``// of tree of every k'th level``void` `swapEveryKLevel(Node* root, ``int` `k){``    ``int` `level = 1;``    ``queue q;``    ``q.push(root);``    ``while``(!q.empty()){``        ``int` `n = q.size();``        ``for``(``int` `i = 0; ileft, &temp->right);``            ``}``            ``if``(temp->left != NULL) q.push(temp->left);``            ``if``(temp->right != NULL) q.push(temp->right);``        ``}``        ``level++;``    ``}``}` `// function to print inorder traversal``void` `inorder(Node* root){``    ``if``(root == NULL) ``return``;``    ``inorder(root->left);``    ``cout<data<<``" "``;``    ``inorder(root->right);``}` `//driver code``int` `main(){``    ``/*    1``        ``/   \``       ``2     3``     ``/      /  \``    ``4      7    8   */``    ``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 :"``<

## Java

 `// Java program swap nodes``import` `java.util.*;` `public` `class` `Main { ``// A Binary Tree Node``  ``static` `class` `Node {``    ``int` `data;``    ``Node left, right;` `    ``Node(``int` `data)``    ``{``      ``this``.data = data;``      ``left = right = ``null``;``    ``}``  ``};` `  ``// a utility function swap left-node and right node``  ``// of tree of every k'th level``  ``static` `void` `swapEveryKLevel(Node root, ``int` `k)``  ``{``    ``int` `level = ``1``;``    ``Queue q = ``new` `LinkedList();``    ``q.add(root);``    ``while` `(!q.isEmpty()) {``      ``int` `n = q.size();``      ``for` `(``int` `i = ``0``; i < n; i++) {``        ``Node temp = q.remove();``        ``if` `((level + ``1``) % k == ``0``) {``          ``Node tmp = temp.left;``          ``temp.left = temp.right;``          ``temp.right = tmp;``        ``}``        ``if` `(temp.left != ``null``)``          ``q.add(temp.left);``        ``if` `(temp.right != ``null``)``          ``q.add(temp.right);``      ``}``      ``level++;``    ``}``  ``}` `  ``// function to print inorder traversal``  ``static` `void` `inorder(Node root)``  ``{``    ``if` `(root == ``null``)``      ``return``;``    ``inorder(root.left);``    ``System.out.print(root.data + ``" "``);``    ``inorder(root.right);``  ``}` `  ``// driver code``  ``public` `static` `void` `main(String[] args)``  ``{` `    ``/*    1``            ``/   \``           ``2     3``         ``/      /  \``        ``4      7    8   */``    ``Node root = ``new` `Node(``1``);``    ``root.left = ``new` `Node(``2``);``    ``root.right = ``new` `Node(``3``);``    ``root.left.left = ``new` `Node(``4``);``    ``root.right.right = ``new` `Node(``8``);``    ``root.right.left = ``new` `Node(``7``);` `    ``int` `k = ``2``;``    ``System.out.println(``"Before swap node :"``);``    ``inorder(root);` `    ``swapEveryKLevel(root, k);` `    ``System.out.println(``"\nAfter swap Node :"``);``    ``inorder(root);``  ``}``}` `// This code is contributed by divyansh2212`

## Python3

 `# Python program for the above approach` `# struct of binary tree node``class` `Node:``    ``def` `__init__(``self``, data):``        ``self``.data ``=` `data``        ``self``.left ``=` `None``        ``self``.right ``=` `None` `# a utility function to swap left-node and right node``# of tree of every k'th level``def` `swapEveryKLevel(root, k):``    ``level ``=` `1``    ``q ``=` `[]``    ``q.append(root)``    ``while` `q:``        ``n ``=` `len``(q)``        ``for` `i ``in` `range``(n):``            ``temp ``=` `q.pop(``0``)``            ``if` `(level``+``1``) ``%` `k ``=``=` `0``:``                ``temp.left, temp.right ``=` `temp.right, temp.left``            ``if` `temp.left !``=` `None``:``                ``q.append(temp.left)``            ``if` `temp.right !``=` `None``:``                ``q.append(temp.right)``        ``level ``+``=` `1` `# function to print inorder traversal``def` `inorder(root):``    ``if` `root ``=``=` `None``:``        ``return``    ``inorder(root.left)``    ``print``(root.data, end``=``" "``)``    ``inorder(root.right)` `# Driver code``"""    1``    ``/   \``   ``2     3`` ``/      /  \``4      7    8   """``root ``=` `Node(``1``)``root.left ``=` `Node(``2``)``root.right ``=` `Node(``3``)``root.left.left ``=` `Node(``4``)``root.right.right ``=` `Node(``8``)``root.right.left ``=` `Node(``7``)` `k ``=` `2``print``(``"Before swap node :"``)``inorder(root)` `swapEveryKLevel(root, k)` `print``(``"\nAfter swap Node :"` `)``inorder(root)``# contributed by akashish__`

## C#

 `// C# program swap nodes``using` `System;``using` `System.Collections.Generic;` `class` `GFG``{` `    ``// A Binary Tree Node``    ``public` `class` `Node``    ``{``        ``public` `int` `data;``        ``public` `Node left, right;``    ``};``    ` `    ``// function to create a new tree node``    ``static` `Node newNode(``int` `data)``    ``{``        ``Node temp = ``new` `Node();``        ``temp.data = data;``        ``temp.left = temp.right = ``null``;``        ``return` `temp;``    ``}``    ` `    ``// a utility function swap left-node and right node``    ``// of tree of every k'th level``    ``static` `void` `swapEveryKLevel(Node root, ``int` `k)``    ``{``        ``int` `level = 1;``        ``Queue q = ``new` `Queue();``        ``q.Enqueue(root);``        ``while``(q.Count!=0){``            ``int` `n = q.Count;``            ``for``(``int` `i = 0; i

## Javascript

 `// Javascript program for the above approach` `// struct of binary tree node``class Node{``    ``constructor(data)``    ``{``        ``this``.data=data;``        ``this``.left=``null``;``        ``this``.right=``null``;``    ``}``}` `// a utility function swap left-node and right node``// of tree of every k'th level``function` `swapEveryKLevel(root, k){``    ``let level = 1;``    ``let q=[];``    ``q.push(root);``    ``while``(q.length){``        ``let n = q.length;``        ``for``(let i = 0; iAfter swap Node :"` `);``inorder(root);`

Output

```Before swap node :
4 2 1 7 3 8
After swap Node :
7 3 8 1 4 2 ```

Time Complexity: O(N) where N is the Number of nodes in a given binary tree.
Auxiliary Space: O(N) due to queue data structure.

My Personal Notes arrow_drop_up