Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Compare Leaf Traversal

Medium Acceptance 77.95% Points 30.00

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?
Companies
Intuit Deloitte
Topics
Tree Traversal Binary Tree
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions