Program to check whether two trees can be formed by swapping nodes or not in Python

Binary trees can sometimes be transformed into each other by swapping left and right subtrees at any node. This problem checks whether two given trees can be made identical through such swapping operations.

Algorithm Overview

The solution uses level-order traversal (BFS) to compare both trees level by level. At each level, we check if the node values can match either in the same order or in reverse order (indicating a possible swap).

Step-by-Step Approach

  • Use two queues to store nodes from both trees level by level

  • For each level, collect node values and child nodes

  • Compare values at each level − they should match either directly or in reverse order

  • Continue until all levels are processed

Implementation

class TreeNode:
    def __init__(self, data, left=None, right=None):
        self.val = data
        self.left = left
        self.right = right

class Solution:
    def solve(self, root0, root1):
        # Initialize queues with root nodes
        que1 = [root0]
        que2 = [root1]
        
        while que1 and que2:
            # Lists to store nodes for next level
            temp1 = []
            temp2 = []
            values1 = []
            values2 = []
            
            # Check if both levels have same number of nodes
            if len(que1) != len(que2):
                return False
            
            # Process current level nodes
            for i in range(len(que1)):
                values1.append(que1[i].val)
                values2.append(que2[i].val)
                
                # Add children to temporary lists (right first, then left)
                if que1[i].right:
                    temp1.append(que1[i].right)
                if que1[i].left:
                    temp1.append(que1[i].left)
                    
                if que2[i].right:
                    temp2.append(que2[i].right)
                if que2[i].left:
                    temp2.append(que2[i].left)
            
            # Check if values match directly or in reverse order
            if values1 != values2:
                if values1 != values2[::-1]:
                    return False
            
            # Move to next level
            que1 = temp1
            que2 = temp2
        
        return True

# Example usage
ob = Solution()

# Create first tree
root = TreeNode(2)
root.right = TreeNode(4)
root.right.left = TreeNode(3)
root.right.right = TreeNode(5)

# Create second tree
root1 = TreeNode(2)
root1.left = TreeNode(4)
root1.left.left = TreeNode(3)
root1.left.right = TreeNode(5)

print(ob.solve(root, root1))
True

How It Works

The algorithm processes both trees level by level:

  • Level 0: Both trees have root node with value 2

  • Level 1: Tree1 has [4], Tree2 has [4] − direct match

  • Level 2: Tree1 has [3,5], Tree2 has [3,5] − direct match

If at any level the values don't match directly or in reverse order, the trees cannot be made identical through swapping.

Time and Space Complexity

  • Time Complexity: O(n) where n is the number of nodes

  • Space Complexity: O(w) where w is the maximum width of the tree

Conclusion

This solution efficiently determines if two binary trees can be made identical by swapping left and right subtrees. It uses level-order traversal and checks if node values at each level match either directly or in reverse order.

---
Updated on: 2026-03-25T11:41:46+05:30

233 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements