LeetCode Entry

226. Invert Binary Tree

18.02.2023 easy 2023 kotlin

Let's write a recursive one-liner.

226. Invert Binary Tree easy

blog post

    fun invertTree(root: TreeNode?): TreeNode? =
        root?.apply { left = invertTree(right).also { right = invertTree(left) } }

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/122

Intuition

Walk tree with Depth-First Search and swap each left and right nodes.

Approach

Let’s write a recursive one-liner.

Complexity

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