본문 바로가기
Algorithm/LeetCode

[LeetCode] Symmetric Tree (Kotlin)

by dvid 2023. 1. 14.

https://leetcode.com/problems/symmetric-tree

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

fun isEqual(left: TreeNode?, right: TreeNode?): Boolean {
    if (left == null && right == null) {
        return true
    }
    if (left == null || right == null) {
        return false
    }
    if (left.`val` != right.`val`) {
        return false
    }
    return isEqual(left.left, right.right) && isEqual(left.right, right.left)
}

재귀를 사용하여 쉽게 풀 수 있다.

댓글