08.12.2023
606. Construct String from Binary Tree easy
blog post
youtube
Join me on Telegram
https://t.me/leetcode_daily_unstoppable/432
Problem TLDR
Pre-order binary tree serialization
Intuition
Let’s write a recursive solution.
Complexity
Time complexity:
O(n)Space complexity:
O(n)
Code
fun tree2str(root: TreeNode?): String = root?.run {
val left = tree2str(left)
val right = tree2str(right)
val curr = "${`val`}"
if (left == "" && right == "") curr
else if (right == "") "$curr($left)"
else "$curr($left)($right)"
} ?: ""