9.01.2024
872. Leaf-Similar Trees easy
blog post
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)