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)
}
재귀를 사용하여 쉽게 풀 수 있다.
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode] Majority Element - (Kotlin) (0) | 2023.01.20 |
---|---|
[LeetCode] Valid Palindrome - (Kotlin) (0) | 2023.01.16 |
[LeetCode] Convert Sorted Array to Binary Search Tree (Kotlin) (0) | 2023.01.15 |
[LeetCode] Merge Sorted Array (Kotlin) (0) | 2023.01.14 |
[LeetCode] Two Sum (Kotlin) (0) | 2022.12.02 |
댓글