Skip to content
Decoder

Leaf-Similar Trees

Easy

Problem

The leaf sequence of a binary tree is the list of its leaf values (nodes with no children), read from left to right.

Given two binary trees root1 and root2, return True if their leaf sequences are the same, and False otherwise. The trees themselves can have completely different shapes.

Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.

Example 1

Input
root1 = [1, 2, 3], root2 = [7, 8, 3, 2]
Output
True
Why
both have leaves 2, 3

Example 2

Input
root1 = [1, 2, 3], root2 = [1, 3, 2]
Output
False
Why
2, 3 versus 3, 2

Example 3

Input
root1 = [1, 2, 3], root2 = [1, 2]
Output
False

Constraints

  • 1 <= number of nodes in each tree <= 200
  • 0 <= Node.val <= 200

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.