Leaf-Similar Trees — LeetCode 872 Python Solution

EasyTreeDepth-First SearchBinary Tree
Problem
#872
Reading time
4 min

The problem

Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence. For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).

Example

Input
root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]
Output
true

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
        def dfs(root: Optional[TreeNode], nums: List[int]) -> None:
            if root.left == root.right:
                nums.append(root.val)
                return
            if root.left:
                dfs(root.left, nums)
            if root.right:
                dfs(root.right, nums)

        l1, l2 = [], []
        dfs(root1, l1)
        dfs(root2, l2)
        return l1 == l2

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 872. Leaf-Similar Trees is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On a study list

This problem is on LeetCode 75.

Frequently asked questions

How hard is LeetCode 872. Leaf-Similar Trees?
LeetCode 872. Leaf-Similar Trees is rated Easy on LeetCode.
What is the time complexity of LeetCode 872. Leaf-Similar Trees?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 872. Leaf-Similar Trees?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 872. Leaf-Similar Trees cover?
LeetCode 872. Leaf-Similar Trees is tagged Tree, Depth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview