LeetCode Entry

606. Construct String from Binary Tree

08.12.2023 easy 2023 kotlin

Pre-order binary tree serialization

606. Construct String from Binary Tree easy blog post substack youtube image.png

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)"
    } ?: ""