Given a binary tree and integer value k, the task is to swap sibling nodes of every k’th level where k >= 1.
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
Before swap node : 4 2 1 7 3 8 After swap Node : 7 3 8 1 4 2
This article is contributed by Nishant_singh(pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Difference between sums of odd level and even level nodes of a Binary Tree
- Pairwise Swap leaf nodes in a binary tree
- Count nodes with two children at level L in a Binary Tree
- Print nodes between two given level numbers of a binary tree
- Print all the nodes except the leftmost node in every level of the given binary tree
- Print extreme nodes of each level of Binary Tree in alternate order
- Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree
- Print even positioned nodes of even levels in level order of the given binary tree
- Recursive Program to Print extreme nodes of each level of Binary Tree in alternate order
- Difference between sums of odd position and even position nodes for each level of a Binary Tree
- Minimum swap required to convert binary tree to binary search tree
- Count the number of nodes at given level in a tree using BFS.
- Sum of nodes at k-th level in a tree represented as string
- Level with maximum number of nodes using DFS in a N-ary tree
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap