2023年9月4日 星期一

【LeetCode】【Kotlin】226. Invert Binary Tree


class Solution {
    fun invertTree(root: TreeNode?): TreeNode? {
        if(root == null) return null
        if(root.left != null) invertTree(root.left) //將左子樹送去處理
        if(root.right != null) invertTree(root.right) //將右子樹送去處理

        //交換左右子樹
        val tempNode = root.left 
        root.left = root.right
        root.right = tempNode

        return root
    }
}

簡化版 :
class Solution {
    fun invertTree(root: TreeNode?): TreeNode? {
        if(root == null) return null
      
        val tempNode = invertTree(root.left)
        root.left = invertTree(root.right)
        root.right = tempNode

        return root
    }
}

0 comments:

張貼留言