Recca Chao 的 gitHub page

推廣網站開發,包含 Laravel 和 Kotlin 後端撰寫、自動化測試、讀書心得等。Taiwan Kotlin User Group 管理員。

View on GitHub

Kotlin Leetcode - 101. Symmetric Tree

題目連接

class Solution {  
    fun isSymmetric(root: TreeNode?): Boolean {  
    }  
}

解題思路

這題是樹的處理

我們可以用遞迴的方式進行比較

Kotlin 參考解答

class Solution {
    fun isSymmetric(root: TreeNode?): Boolean {
        if (root == null) { return true }
        return isSubtreeSymmetric(root.left, root.right)
    }
    
    private fun isSubtreeSymmetric(left: TreeNode?, right: TreeNode?): Boolean {
        if (left == null && right == null) {
            return true
        }
        
        if (left?.`val` != right?.`val`) {
            return false
        }
        
        return isSubtreeSymmetric(left?.left, right?.right)
            && isSubtreeSymmetric(left?.right, right?.left)
    }
}

when 的寫法

class Solution {
    fun isSymmetric(root: TreeNode?): Boolean {
        if (root == null) { return true }
        return isSubtreeSymmetric(root.left, root.right)
    }

    private fun isSubtreeSymmetric(left: TreeNode?, right: TreeNode?): Boolean =
        when {
            left == null && right == null ->  true
            left?.`val` != right?.`val` -> false
            else -> isSubtreeSymmetric(left?.left, right?.right)
                && isSubtreeSymmetric(left?.right, right?.left)
        }
    
}

回到 leetcode 列表