Pairwise Swap leaf nodes in a binary tree
Last Updated :
18 Sep, 2023
Given a binary tree, we need to write a program to swap leaf nodes in the given binary tree pairwise starting 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:
CPP
/* C++ program to pairwise swap
leaf nodes from left to right */
#include <bits/stdc++.h>
using namespace std;
// A Binary Tree Node
struct Node
{
int data;
struct Node *left, *right;
};
// function to swap two Node
void Swap(Node **a, Node **b)
{
Node * temp = *a;
*a = *b;
*b = temp;
}
// two pointers to keep track of
// first and second nodes in a pair
Node **firstPtr;
Node **secondPtr;
// function to pairwise swap leaf
// nodes from left to right
void pairwiseSwap(Node **root, int &count)
{
// if node is null, return
if (!(*root))
return;
// if node is leaf node, increment count
if(!(*root)->left&&!(*root)->right)
{
// initialize second pointer
// by current node
secondPtr = root;
// increment count
count++;
// if count is even, swap first
// and second pointers
if (count%2 == 0)
Swap(firstPtr, secondPtr);
else
// if count is odd, initialize
// first pointer by second pointer
firstPtr = secondPtr;
}
// if left child exists, check for leaf
// recursively
if ((*root)->left)
pairwiseSwap(&(*root)->left, count);
// if right child exists, check for leaf
// recursively
if ((*root)->right)
pairwiseSwap(&(*root)->right, count);
}
// Utility 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;
}
// function to print inorder traversal
// of binary tree
void printInorder(Node* node)
{
if (node == NULL)
return;
/* first recur on left child */
printInorder(node->left);
/* then print the data of node */
printf("%d ", node->data);
/* now recur on right child */
printInorder(node->right);
}
// Driver program to test above functions
int main()
{
// Let us create binary tree shown in
// above diagram
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(8);
root->right->left->left = newNode(6);
root->right->left->right = newNode(7);
root->right->right->left = newNode(9);
root->right->right->right = newNode(10);
// print inorder traversal before swapping
cout << "Inorder traversal before swap:\n";
printInorder(root);
cout << "\n";
// variable to keep track
// of leafs traversed
int c = 0;
// Pairwise swap of leaf nodes
pairwiseSwap(&root, c);
// print inorder traversal after swapping
cout << "Inorder traversal after swap:\n";
printInorder(root);
cout << "\n";
return 0;
}
Java
/* Java program to pairwise swap
leaf nodes from left to right */
// A binary Tree Node
class Node {
int data;
Node left, right;
Node(int data)
{
this.data = data;
left = null;
right = null;
}
}
class Main {
// two pointers to keep track of
// first and second nodes in a pair
static Node firstPtr = null;
static Node secondPtr = null;
// variable to keep track
// of leafs traversed
static int count = 0;
// function to pairwise swap leaf
// nodes from left to right
public static void pairWiseSwap(Node root)
{
// if node is null, return
if (root == null)
return;
// if node is leaf node, increment count
if (root.left == null && root.right == null) {
// initialize second pointer
// by current node
secondPtr = root;
// increment count
count++;
// if count is even, swap first
// and second pointers
if (count % 2 == 0) {
int temp = firstPtr.data;
firstPtr.data = secondPtr.data;
secondPtr.data = temp;
}
// if count is odd, initialize
// first pointer by second pointer
else
firstPtr = secondPtr;
}
// if left child exists, check for leaf
// recursively
if (root.left != null)
pairWiseSwap(root.left);
// if right child exists, check for leaf
// recursively
if (root.right != null)
pairWiseSwap(root.right);
}
// Utility function to create a new tree node
public static Node newNode(int data)
{
return new Node(data);
}
// function to print inorder traversal
// of binary tree
public static void printInorder(Node node)
{
if (node == null)
return;
/* first recur on left child */
printInorder(node.left);
/* then print the data of node */
System.out.print(node.data + " ");
/* now recur on right child */
printInorder(node.right);
}
// Driver program to test above functions
public static void main(String[] args)
{
// Let us create binary tree shown in
// above diagram
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.right.left = newNode(5);
root.right.right = newNode(8);
root.right.left.left = newNode(6);
root.right.left.right = newNode(7);
root.right.right.left = newNode(9);
root.right.right.right = newNode(10);
// print inorder traversal before swapping
System.out.print(
"Inorder traversal before swap : ");
printInorder(root);
pairWiseSwap(root);
// print inorder traversal after swapping
System.out.println();
System.out.print("Inorder traversal after swap: ");
printInorder(root);
}
}
Python3
# Python program to pairwise swap
# leaf nodes from left to right
# a binary tree node
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# function to swap two node
def Swap(a, b):
temp = a.data
a.data = b.data
b.data = temp
# two pointers to keep track of
# first and second nodes in pair
firstPtr = None
secondPtr = None
# functiont o pairwise swap leaf
# nodes from left to right
count = 0
def pairwiseSwap(root):
# if node is null, return
if(root is None):
return
# if node is leaf node, incrrement count
if(root.left is None and root.right is None):
global count, firstPtr, secondPtr
# initialize second pointer by current node
secondPtr = root
# increment count
count += 1
# if count is even, swap first
# and second pointers
if(count % 2 == 0):
Swap(firstPtr, secondPtr)
else:
# if count is odd, initialize
# first pointer by second pointer
firstPtr = secondPtr
# if left child exists, check for leaf
# recursively
if(root.left is not None):
pairwiseSwap(root.left)
# if right child exists, check for leaf
# recursively
if(root.right is not None):
pairwiseSwap(root.right)
# utility function to create a new node
def newNode(data):
return Node(data)
# function to print inorder traversal of binary tree
def printInorder(node):
if(node is None):
return
# first recur on left child
printInorder(node.left)
# then print the data of node
print(node.data, end=" ")
# now recur on right child
printInorder(node.right)
# driver program to test above function
# let us create a binary tree shownin above diagram
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.right.left = newNode(5)
root.right.right = newNode(8)
root.right.left.left = newNode(6)
root.right.left.right = newNode(7)
root.right.right.left = newNode(9)
root.right.right.right = newNode(10)
# print Inorder traversal before swapping
print("Inorder traversal before swap : ")
printInorder(root)
# variable to keep track of leafs traversed
# pairwise swap of leaf nodes
pairwiseSwap(root)
# print Inorder traversal after swapping
print("\nInorder traversal after swap : ")
printInorder(root)
C#
// C# Program to pairwise swap
// leaf nodes from left to right
// in a binary tree node
using System;
public class Node{
public int data;
public Node left, right;
public Node(int item){
data = item;
left = right = null;
}
}
public class BinaryTree{
static Node firstPtr;
static Node secondPtr;
// function to swap two node
static void Swap(Node a, Node b){
int temp = a.data;
a.data = b.data;
b.data = temp;
}
// function to pairwise swap leaf
// nodes from left to right
static int count = 0;
static void pairwiseSwap(Node root){
// if node is null, return
if(root == null) return;
// if node is leaf node, increment count
if(root.left == null && root.right == null){
// initialize second pointer by current node
secondPtr = root;
// increment count
count += 1;
// if count is even, swap first
// and second pointers
if(count % 2 == 0){
Swap(firstPtr, secondPtr);
}else{
// if count is odd, initialize
// first pointer by second pointer
firstPtr = secondPtr;
}
}
// if left child exists, check for leaf
// recursively
if(root.left != null){
pairwiseSwap(root.left);
}
// if right child exists, check for leaf
// recursively
if(root.right != null){
pairwiseSwap(root.right);
}
}
// utility function to create a new tree node
static Node newNode(int data){
return new Node(data);
}
// function to print inorder traversal of binary tree
static void printInorder(Node node){
if(node == null) return;
// first recur on left child
printInorder(node.left);
// then print the data of node
Console.Write(node.data + " ");
// now recur on right child
printInorder(node.right);
}
// driver program to test above function
static public void Main (){
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.right.left = newNode(5);
root.right.right = newNode(8);
root.right.left.left = newNode(6);
root.right.left.right = newNode(7);
root.right.right.left = newNode(9);
root.right.right.right = newNode(10);
// print inorder traversal before swapping
Console.WriteLine("Inorder Traversal before swap : ");
printInorder(root);
Console.WriteLine();
// variable to keep track of leafs traversal
// pairwise swap of leaf nodes
pairwiseSwap(root);
// print inorder traversal after swapping
Console.WriteLine("Inorder traversal after swap : ");
printInorder(root);
}
}
// this code is contributed by Kirti Agarwal(kirtiagarwal23121999)
JavaScript
// JavaScript program to pairwise swap leaf
// nodes from left to right
// a binary tree node
class Node{
constructor(data){
this.data = data;
this.left = null;
this.right = null;
}
}
// function to swap two node
function Swap(a, b){
let temp = a.data;
a.data = b.data;
b.data = temp;
}
// two pointers to keep track of
// first and second nodes in pair
let firstPrt;
let secondPtr;
// function to pairwise swap leaf
// nodes from left to right
let count = 0;
function pairwiseSwap(root)
{
// if node is null, return
if(root == null) return;
// if node is leaf node, increment count
if(root.left == null && root.right == null){
// initialize second pointer by current node
secondPtr = root;
// increment count
count++;
// if count is even, swap first
// and second pointers
if(count % 2 == 0){
Swap(firstPtr, secondPtr);
}
else{
// if count is odd, initialize
// first pointer by second pointer
firstPtr = secondPtr;
}
}
// if left child exists, check for leaf
// recursively
if(root.left != null){
pairwiseSwap(root.left);
}
// if right child exists, check for leaf
// recursively
if(root.right != null){
pairwiseSwap(root.right);
}
}
// utility function to create a new tree node
function newNode(data){
return new Node(data);
}
// function to print inorder traversal of bianry tree
function printInorder(node){
if(node == null)
return;
// first recur on left child
printInorder(node.left);
// then print the data of node
console.log(node.data + " ");
// now recur on right child
printInorder(node.right);
}
// driver program to test above functions
// let us create binary tree shown in above diagram
let root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.right.left = newNode(5);
root.right.right = newNode(8);
root.right.left.left = newNode(6);
root.right.left.right = newNode(7);
root.right.right.left = newNode(9);
root.right.right.right = newNode(10);
// print inorder traversal before swapping
console.log("Inorder traversal before swap: ");
printInorder(root);
// variable to keep track of leafs traversed
// pairwise swap of leaf nodes
pairwiseSwap(root);
// print inorder traversal after swapping
console.log("Inorder traversal after swap: ");
printInorder(root);
// this code is contributed by Yash Agarwal(yashagarwal2852002)
OutputInorder 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(n)
Similar Reads
Leaf nodes from Preorder of a Binary Search Tree
Given Preorder traversal of a Binary Search Tree. Then the task is to print leaf nodes of the Binary Search Tree from the given preorder.Examples: Input: preorder[] = [4, 2, 1, 3, 6, 5]Output: [1, 3, 5]Explaination: 1, 3 and 5 are the leaf nodes as shown in the figure. Input: preorder[] = [5, 2, 10]
14 min read
Count Non-Leaf nodes in a Binary Tree
Given a Binary tree, count the total number of non-leaf nodes in the tree Examples: Input : Output :2 Explanation In the above tree only two nodes 1 and 2 are non-leaf nodesRecommended PracticeCount Non-Leaf Nodes in TreeTry It! We recursively traverse the given tree. While traversing, we count non-
10 min read
Minimum swaps to sort the leaf nodes in a Perfect Binary Tree
Given a perfect binary tree of height N and an array of length 2N which represents the values of leaf nodes from left to right. An operation is defined as choosing any non-leaf vertex of the tree and swapping its left and right sons (along with their subtrees). Find the minimum number of such operat
10 min read
Print left and right leaf nodes separately in Binary Tree
Given a binary tree, the task is to print left and right leaf nodes separately. Examples: Input: 0 / \ 1 2 / \ 3 4 Output: Left Leaf Nodes: 3 Right Leaf Nodes: 4 2 Input: 0 \ 1 \ 2 \ 3 Output: Left Leaf Nodes: None Right Leaf Nodes: 3 Approach: Check if given node is null. If null, then return from
8 min read
Sum of all leaf nodes of binary tree
Given a binary tree, find the sum of all the leaf nodes.Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 Output : Sum = 4 + 5 + 8 + 7 = 24 Recommended PracticeSum of Leaf NodesTry It! The idea is to traverse the tree in any fashion and check if the node is the leaf node or not. If the node is the lea
5 min read
All Leaves of a Bnary Tree - Print in Order
Given a binary tree, we need to print all leaf nodes of the given binary tree from left to right. That is, the nodes should be printed in the order they appear from left to right in the given tree. For Example, Input : Root of the below treeOutput : 4 6 7 9 10Corner Cases : For a tree with single no
11 min read
Print Root-to-Leaf Paths in a Binary Tree
Given a Binary Tree of nodes, the task is to find all the possible paths from the root node to all the leaf nodes of the binary tree.Example:Input:Output: 1 2 41 2 51 3 Using Recursion - O(n) Time and O(h) SpaceIn the recursive approach to print all paths from the root to leaf nodes, we can perform
2 min read
Print all internal nodes of a Binary tree
Given a Binary tree, the task is to print all the internal nodes in a tree. An internal node is a node which carries at least one child or in other words, an internal node is not a leaf node. Here we intend to print all such internal nodes in level order. Consider the following Binary Tree: Input: O
7 min read
Swap Nodes in Binary tree of every k'th level
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 swa
14 min read
Print all nodes in a binary tree having K leaves
Given a binary tree and a integer value K, the task is to find all nodes in given binary tree having K leaves in subtree rooted with them. Examples : // For above binary tree Input : k = 2 Output: {3} // here node 3 have k = 2 leaves Input : k = 1 Output: {6} // here node 6 have k = 1 leaveRecommend
7 min read