Check if all levels of two trees are anagrams or not in Python

In this problem, we need to check if each level of two binary trees contains the same elements (forming anagrams). Two strings are anagrams if they contain the same characters in different order. Similarly, two tree levels are anagrams if they contain the same values in any order.

The approach uses level-order traversal (BFS) to compare each level of both trees simultaneously.

Tree 1: 5 6 7 9 8 Tree 2: 5 7 6 8 9 Level 0: [5] Level 1: [6,7] Level 2: [9,8] Level 0: [5] Level 1: [7,6] Level 2: [8,9]

Algorithm

The algorithm follows these steps ?

  • Use two queues to perform level−order traversal on both trees simultaneously
  • For each level, collect all node values into separate lists
  • Sort both lists and compare them
  • If any level comparison fails, return False
  • If all levels match, return True

Implementation

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

def make_tree(elements):
    if not elements:
        return None
    
    tree = TreeNode(elements[0])
    for element in elements[1:]:
        insert_value(tree, element)
    return tree

def insert_value(root, value):
    queue = [root]
    
    while queue:
        node = queue.pop(0)
        
        if not node.left:
            if value is not None:
                node.left = TreeNode(value)
            else:
                node.left = TreeNode(0)
            break
        else:
            queue.append(node.left)
            
        if not node.right:
            if value is not None:
                node.right = TreeNode(value)
            else:
                node.right = TreeNode(0)
            break
        else:
            queue.append(node.right)

def check_anagram_levels(tree1, tree2):
    # Handle edge cases
    if tree1 is None and tree2 is None:
        return True
    if tree1 is None or tree2 is None:
        return False
    
    queue1 = [tree1]
    queue2 = [tree2]
    
    while queue1 and queue2:
        size1 = len(queue1)
        size2 = len(queue2)
        
        # If level sizes differ, trees can't have anagram levels
        if size1 != size2:
            return False
        
        if size1 == 0:
            break
            
        curr_level1 = []
        curr_level2 = []
        
        # Process all nodes at current level
        for _ in range(size1):
            node1 = queue1.pop(0)
            node2 = queue2.pop(0)
            
            # Add children to queue for next level
            if node1.left:
                queue1.append(node1.left)
            if node1.right:
                queue1.append(node1.right)
                
            if node2.left:
                queue2.append(node2.left)
            if node2.right:
                queue2.append(node2.right)
            
            # Collect current level values
            curr_level1.append(node1.value)
            curr_level2.append(node2.value)
        
        # Check if current levels are anagrams
        curr_level1.sort()
        curr_level2.sort()
        
        if curr_level1 != curr_level2:
            return False
    
    return True

# Example usage
tree1 = make_tree([5, 6, 7, 9, 8])
tree2 = make_tree([5, 7, 6, 8, 9])

result = check_anagram_levels(tree1, tree2)
print(f"Are tree levels anagrams? {result}")

The output of the above code is ?

Are tree levels anagrams? True

How It Works

For the given example:

  • Level 0: Tree1 = [5], Tree2 = [5] ? Sorted: [5] = [5] ?
  • Level 1: Tree1 = [6,7], Tree2 = [7,6] ? Sorted: [6,7] = [6,7] ?
  • Level 2: Tree1 = [9,8], Tree2 = [8,9] ? Sorted: [8,9] = [8,9] ?

Since all levels contain the same elements when sorted, the function returns True.

Time and Space Complexity

  • Time Complexity: O(N log N) where N is the total number of nodes, due to sorting at each level
  • Space Complexity: O(W) where W is the maximum width of the tree for the queues

Conclusion

This algorithm efficiently checks if corresponding levels of two binary trees are anagrams using level-order traversal and sorting. The approach handles trees of any structure and correctly identifies when levels contain the same elements in different arrangements.

Updated on: 2026-03-25T14:56:14+05:30

292 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements