LeetCode Entry

872. Leaf-Similar Trees

9.01.2024 easy 2024 kotlin

Are leafs sequences equal for two trees.

872. Leaf-Similar Trees easy blog post substack youtube image.png

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/466

Problem TLDR

Are leafs sequences equal for two trees.

Intuition

Let’s build a leafs lists and compare them.

Approach

Let’s use recursive function.

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(n)\)

Code


  fun leafs(n: TreeNode?): List<Int> = n?.run {
    (leafs(left) + leafs(right))
    .takeIf { it.isNotEmpty() } ?: listOf(`val`)
  } ?: listOf()
  fun leafSimilar(root1: TreeNode?, root2: TreeNode?) =
    leafs(root1) == leafs(root2)