Leaf-Similar Trees

Consider all the leaves of a binary tree, from left to right order. The values of those leaves form a leaf value sequence.

Two binary trees are considered leaf-similar if their leaf value sequence is the same.

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

Example 1
        3                    3
       / \                  / \
      5   1                5   1
     / \ / \              / \ / \
    6  2 9  8            6  7 4  2
      / \                       / \
     7   4                     9   8
Inputroot1 = [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]
Outputtrue
Both trees have the same leaf value sequence, so they are leaf-similar.
Example 2
        1           1
       / \         / \
      2   3       3   2
Inputroot1 = [1,2,3], root2 = [1,3,2]
Outputfalse
The first tree has leaf sequence [2, 3], while the second tree has leaf sequence [3, 2], so they are not leaf-similar.

Constraints

  • The number of nodes in each tree will be in the range [1, 200].
  • Both of the given trees will have values in the range [0, 200].

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate