872. Leaf-Similar Trees
Problem
Decide whether two binary trees have the same leaf value sequence (their leaves read left to right).
Example: two trees whose leaves both read 6,7,4,9,8 → true
Collect each tree's leaves left-to-right with a DFS and compare the sequences.
Complexity: O(n + m).
class Solution:
def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
def leaves(node):
if node:
if not node.left and not node.right:
yield node.val
yield from leaves(node.left)
yield from leaves(node.right)
return list(leaves(root1)) == list(leaves(root2))
a = make_tree([3, 5, 1, 6, 2, 9, 8, None, None, 7, 4])
b = make_tree([3, 5, 1, 6, 7, 4, 2, None, None, None, None, None, None, 9, 8])
assert Solution().leafSimilar(a, b) is True
assert Solution().leafSimilar(make_tree([1, 2, 3]), make_tree([1, 3, 2])) is False
assert Solution().leafSimilar(make_tree([1]), make_tree([2, 1])) is True
class Solution {
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
List<Integer> a = new ArrayList<>(), b = new ArrayList<>();
leaves(root1, a);
leaves(root2, b);
return a.equals(b);
}
private void leaves(TreeNode n, List<Integer> out) {
if (n == null) return;
if (n.left == null && n.right == null) out.add(n.val);
leaves(n.left, out);
leaves(n.right, out);
}
}
func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool {
var leaves func(node *TreeNode, out []int) []int
leaves = func(node *TreeNode, out []int) []int {
if node == nil {
return out
}
if node.Left == nil && node.Right == nil {
return append(out, node.Val)
}
return leaves(node.Right, leaves(node.Left, out))
}
a, b := leaves(root1, nil), leaves(root2, nil)
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}