Leaf-Similar Trees - 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).

Two binary trees are considered leaf-similar if their leaf value sequences are the same.

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

Input & Output

Example 1 — Identical Leaf Sequences
$ 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
💡 Note: Both trees have leaf sequence [6,7,4,9,8] when read from left to right, so they are leaf-similar.
Example 2 — Different Leaf Sequences
$ Input: root1 = [1,2,3], root2 = [1,3,2]
Output: false
💡 Note: Tree1 has leaves [2,3] while Tree2 has leaves [3,2]. Different order means not leaf-similar.
Example 3 — Single Node Trees
$ Input: root1 = [1], root2 = [1]
Output: true
💡 Note: Both trees have only one node (which is a leaf) with value 1, so leaf sequences are [1] and [1].

Constraints

  • The number of nodes in each tree will be in the range [1, 200]
  • Both of the given trees will have values in the range [0, 200]

Visualization

Tap to expand
Leaf-Similar Trees: Internal Structure Doesn't Matter3516236521Leaves: [6, 2, 1]Leaves: [6, 2, 1]Same leaf sequence → Trees are leaf-similar!Tree 1Tree 2
Understanding the Visualization
1
Input Trees
Two binary trees with different internal structures
2
Extract Leaves
Read leaf values from left to right in both trees
3
Compare
Check if leaf sequences are identical
Key Takeaway
🎯 Key Insight: Trees are leaf-similar if their leaf value sequences match, regardless of internal structure
Asked in
Google 25 Amazon 20 Facebook 15
72.0K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen