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
Input: Two binary tree root nodes
Output: Boolean indicating if the trees are leaf-similar
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 root2Output: 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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code