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 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.
- Sum of all leaf nodes of binary tree
- Count Non-Leaf nodes in a Binary Tree
- Product of all leaf nodes of binary tree
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- Print the nodes of binary tree as they become the leaf node
- Program to count leaf nodes in a binary tree
- Maximum sum of leaf nodes among all levels of the given binary tree
- Print all leaf nodes of a Binary Tree from left to right
- Print all leaf nodes of a binary tree from right to left
- Maximum sum of non-leaf nodes among all levels of the given binary tree
- Swap Nodes in Binary tree of every k'th level
- Print leaf nodes in binary tree from left to right using one stack
- Iterative program to count leaf nodes in a Binary Tree
- Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
- Find height of a special binary tree whose leaf nodes are connected