Invert Binary Tree

I initially tried to solve this iteratively but I couldn’t figure out the solution. Recursive approach seems to be the best and easiest way.

/**
 * Example:
 * var ti = TreeNode(5)
 * var v = ti.`val`
 * Definition for a binary tree node.
 * class TreeNode(var `val`: Int) {
 *     var left: TreeNode? = null
 *     var right: TreeNode? = null
 * }
 */

import java.util.*

class Solution {
    fun invertTree(root: TreeNode?): TreeNode? {
        tailrec fun invertTree_(node: TreeNode?): TreeNode?{
            if(node == null) return null
            val left = node.left
            node.left = invertTree_(node.right)
            node.right = invertTree_(left)
            return node
        }
        
        invertTree_(root)
                
        return root
    }
}
Runtime: 140 ms, faster than 63.16% of Kotlin online submissions for Invert Binary Tree.
Memory Usage: 31.6 MB, less than 100.00% of Kotlin online submissions for Invert Binary Tree.
comments powered by Disqus