SDE & MLE Prep

872. Leaf-Similar Trees

Problem

Decide whether two binary trees have the same leaf value sequence (their leaves read left to right).

Example: two trees whose leaves both read 6,7,4,9,8 → true

Collect each tree's leaves left-to-right with a DFS and compare the sequences.

Complexity: O(n + m).

class Solution:
    def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
        def leaves(node):
            if node:
                if not node.left and not node.right:
                    yield node.val
                yield from leaves(node.left)
                yield from leaves(node.right)

        return list(leaves(root1)) == list(leaves(root2))