Leaf-Similar Trees - Problem
Leaf-Similar Trees is a fascinating problem that tests your understanding of binary tree traversal and sequence comparison.

Given two binary trees, we need to determine if they are leaf-similar. Two trees are considered leaf-similar if their leaf value sequences are identical when read from left to right.

The leaf value sequence is formed by collecting all leaf node values in left-to-right order. For example, if a tree has leaves with values [6, 7, 4, 9, 8] when traversed from left to right, that becomes its leaf sequence.

Goal: Return true if the two given trees have the same leaf value sequence, false otherwise.

Input: Two binary tree root nodes root1 and root2
Output: Boolean indicating if the trees are leaf-similar

Input & Output

example_1.py โ€” Basic Similar Trees
$ 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 the same leaf sequence [6,7,4,9,8] when read from left to right, even though their internal structure is different.
example_2.py โ€” Different Leaf Sequences
$ Input: root1 = [1,2,3], root2 = [1,3,2]
โ€บ Output: false
๐Ÿ’ก Note: Tree 1 has leaf sequence [2,3] while tree 2 has leaf sequence [3,2]. The sequences are different, so the trees are not leaf-similar.
example_3.py โ€” Single Node Trees
$ Input: root1 = [1], root2 = [1]
โ€บ Output: true
๐Ÿ’ก Note: Both trees consist of a single node (which is a leaf) with the same value, so they are leaf-similar.

Constraints

  • The number of nodes in each tree is in the range [1, 200]
  • Both trees will have values in the range [0, 200]
  • Both root1 and root2 are guaranteed to be non-null

Visualization

Tap to expand
Library Book ComparisonLibrary 1FictionScienceHistoryArtABCDLibrary 2ReferencePoetryTravelABEDComparison ResultSequence 1: A, B, C, DSequence 2: A, B, E, DNot Similar! (C โ‰  E)Different layouts, but we only care about bottom shelf sequence
Understanding the Visualization
1
Start at Entrance
Begin at the entrance of both libraries with two assistants
2
Find Bottom Shelf Books
Each assistant finds the next bottom-shelf book in left-to-right order
3
Compare Books
Compare the books found by both assistants
4
Continue or Stop
If books match, continue; if different, libraries are not similar
Key Takeaway
๐ŸŽฏ Key Insight: Just like comparing library bottom shelves, we only need to traverse leaves in order and compare them one-by-one, without storing the entire sequence. Early mismatch detection saves both time and space!
Asked in
Amazon 45 Microsoft 32 Google 28 Facebook 21
89.4K Views
Medium Frequency
~15 min Avg. Time
2.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