#872

Leaf-Similar Trees

Easy
TreeDepth-First SearchBinary TreeDepth-First SearchRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(h)
💡

Intuition

Time O(n)Space O(h)

The optimal solution involves using a single traversal for both trees simultaneously. This way, we can compare leaf values as we collect them, avoiding the need for extra space to store them.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a helper function that traverses both trees simultaneously.
  2. 2Step 2: Compare leaf values directly during the traversal.
  3. 3Step 3: Return true if all leaf values match, otherwise return false.
solution.py18 lines
1# Full working Python code
2class TreeNode:
3    def __init__(self, val=0, left=None, right=None):
4        self.val = val
5        self.left = left
6        self.right = right
7
8
9def leafSimilar(root1, root2):
10    def dfs(node1, node2):
11        if not node1 and not node2:
12            return True
13        if not node1 or not node2:
14            return False
15        if not node1.left and not node1.right and not node2.left and not node2.right:
16            return node1.val == node2.val
17        return dfs(node1.left, node2.left) and dfs(node1.right, node2.right)
18    return dfs(root1, root2)

Complexity note: The time complexity is O(n) because we traverse each node once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.

  • 1Leaf values are collected from left to right.
  • 2Direct comparison during traversal can save space.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.