Leaf-Similar Trees

Easy Topics Company Tags

A leaf is a node with no children. Read the leaf values of each tree from left to right. Return true if the two resulting sequences are identical, including their order and repeated values; otherwise return false. The shapes and internal values of the trees may differ.

Each tree is encoded as a level-order array. After the root, each present node contributes left and right child entries in queue order. null marks a missing child, and trailing missing entries may be omitted.

Example 1:

Leaf-Similar Trees, example 1: illustration of the example

Input: root1 = [8,2,5]
root2 = [9,4,5,2]

Output: true

Explanation: Both trees have leaf values [2,5] from left to right. Their internal nodes and shapes differ, but the leaf sequences match.

Example 2:

Leaf-Similar Trees, example 2: illustration of the example

Input: root1 = [8,2,5]
root2 = [9,5,2]

Output: false

Explanation: The first leaf sequence is [2,5], while the second is [5,2]. The same values in a different order do not match.

Example 3:

Leaf-Similar Trees, example 3: illustration of the example

Input: root1 = [4]
root2 = [7,4]

Output: true

Explanation: The single node in the first tree is a leaf with value 4. In the second tree, the root has a left child, so only that child contributes to the leaf sequence [4].

Constraints:

  • Each tree contains between 1 and 200 nodes.
  • 0 <= Node.val <= 200


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.