Given a binary tree, we need to write a program to swap leaf nodes in the given binary tree pairwise starting from from left to right as shown below.
Tree before swapping:
Tree after swapping:
The sequence of leaf nodes in original binary tree from left to right is (4, 6, 7, 9, 10). Now if we try to form pairs from this sequence, we will have two pairs as (4, 6), (7, 9). The last node (10) is unable to form pair with any node and thus left unswapped.
The idea to solve this problem is to first traverse the leaf nodes of the binary tree from left to right.
While traversing the leaf nodes, we maintain two pointers to keep track of first and second leaf nodes in a pair and a variable count to keep track of count of leaf nodes traversed.
Now, if we observe carefully then we see that while traversing if the count of leaf nodes traversed is even, it means that we can form a pair of leaf nodes. To keep track of this pair we take two pointers firstPtr and secondPtr as mentioned above. Every time we encounter a leaf node we initialize secondPtr with this leaf node. Now if the count is odd, we initialize firstPtr with secondPtr otherwise we simply swap these two nodes.
Below is the C++ implementation of above idea:
Inorder traversal before swap: 4 2 1 6 5 7 3 9 8 10 Inorder traversal after swap: 6 2 1 4 5 9 3 7 8 10
Time Complexity: O( n ), where n is the number of nodes in the binary tree.
Auxiliary Space: O( 1 )
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.
- Tree Traversals (Inorder, Preorder and Postorder)
- Find the node with minimum value in a Binary Search Tree
- Write a program to Calculate Size of a tree | Recursion
- Write a Program to Find the Maximum Depth or Height of a Tree
- Write a program to Delete a Tree
- If you are given two traversal sequences, can you construct the binary tree?
- Convert a Binary Tree into its Mirror Tree
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Lowest Common Ancestor in a Binary Search Tree.
- The Great Tree-List Recursion Problem.
- Check sum of Covered and Uncovered nodes of Binary Tree
- Level Order Tree Traversal
- Program to count leaf nodes in a binary tree
- A program to check if a binary tree is BST or not
- Check for Children Sum Property in a Binary Tree