Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Compare Leaf Traversal

Medium Acceptance 77.95% Points 30

You are given the roots of two binary trees. Consider the sequence of leaf values from left to right in each tree, known as the leaf value sequence.

Your task is to determine whether both trees have the same leaf value sequence.

A leaf node is a node with no left or right child.

Return true if both leaf value sequences are identical; otherwise, return false.

Examples
Example 1

image 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
Explanation: Both trees produce the same leaf value sequence: 6, 7, 4, 9, 8.

Example 2

image Input: root1 = [1,2,3], root2 = [1,3,2]
Output: false
Explanation: The first tree's leaf sequence is 2, 3, while the second's is 3, 2. They do not match.

Example 3

image Input: root1 = [1], root2 = [1]
Output: true
Explanation: Both single-node trees have the identical leaf sequence: 1.

Constraints
    • 1 = Number of nodes in each tree = 200
    • -10? = Node.data = 10?
Topics
Tree Traversal Binary Tree
Companies
Intuit Deloitte
Added 08 Aug 2026 77.95% acceptance
Ln 1, Col 1Sign in to save your code
1 2 3 4 5 6 7
1 2 3 4 5 6 7
true