Program to check whether leaves sequences are same of two leaves or not in python

In this problem, we need to check whether two binary trees have the same sequence of leaf nodes when read from left to right. A leaf node is a node that has no left or right children.

So, if the input trees are:

Tree 1 1 3 2 6 Tree 2 1 3 2 6

Then the output will be True as the leaf sequence is [2, 6] for both trees.

Solution Approach

We'll use an inorder traversal to collect leaf nodes from left to right. The algorithm works as follows ?

  • Define a helper function to traverse the tree
  • During traversal, check if a node is a leaf (no left and right children)
  • If it's a leaf, add its value to our result list
  • Compare the leaf sequences of both trees

Implementation

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

class Solution:
    def get_leaves(self, root):
        """Collect leaf nodes from left to right using inorder traversal"""
        leaves = []
        
        def inorder(node):
            if not node:
                return
            
            # Traverse left subtree
            inorder(node.left)
            
            # If it's a leaf node, add to our list
            if not node.left and not node.right:
                leaves.append(node.val)
            
            # Traverse right subtree
            inorder(node.right)
        
        inorder(root)
        return leaves
    
    def solve(self, root1, root2):
        """Check if both trees have the same leaf sequence"""
        leaves1 = self.get_leaves(root1)
        leaves2 = self.get_leaves(root2)
        return leaves1 == leaves2

# Test the solution
ob = Solution()

# Create first tree: 1 -> 3 -> (2, 6)
root1 = TreeNode(1)
root1.right = TreeNode(3)
root1.right.left = TreeNode(2)
root1.right.right = TreeNode(6)

# Create second tree: 1 -> (3 -> 2, 6)
root2 = TreeNode(1)
root2.left = TreeNode(3)
root2.right = TreeNode(6)
root2.left.left = TreeNode(2)

print("Leaf sequence comparison result:", ob.solve(root1, root2))
print("Tree 1 leaves:", ob.get_leaves(root1))
print("Tree 2 leaves:", ob.get_leaves(root2))
Leaf sequence comparison result: True
Tree 1 leaves: [2, 6]
Tree 2 leaves: [2, 6]

How It Works

The solution uses inorder traversal (left ? root ? right) to visit nodes. During traversal, we check if each node is a leaf by verifying it has no children. Since we traverse left before right, leaf nodes are collected in left-to-right order.

Key Points

  • Leaf Node: A node with no left and right children
  • Inorder Traversal: Ensures left-to-right ordering of leaves
  • Time Complexity: O(n) where n is the total number of nodes
  • Space Complexity: O(h) for recursion stack, where h is tree height

Conclusion

This solution efficiently compares leaf sequences by using inorder traversal to collect leaves in left-to-right order. The approach works for any binary tree structure and correctly identifies matching leaf patterns.

Updated on: 2026-03-25T12:50:03+05:30

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements