EasyNo. 0872
Leaf-Similar Trees — LeetCode 872 Python Solution
- Pattern
- Tree Traversal
- Topics
- Tree, Depth-First Search, Binary Tree
- On a study list
- LeetCode 75
- Reading time
- 4 min
- Source
- leetcode.com
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
# 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 == l2Complexity
- Time
- O(V+E)
- Space · auxiliary
- O(V)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0098 | Validate Binary Search Tree | Medium |
| 0099 | Recover Binary Search Tree | Medium |
| 0100 | Same Tree | Easy |
| 0101 | Symmetric Tree | Easy |
| 0104 | Maximum Depth of Binary Tree | Easy |
| 0110 | Balanced Binary Tree | Easy |
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.