Kotlin Leetcode - 101. Symmetric Tree
class Solution {
fun isSymmetric(root: TreeNode?): Boolean {
}
}
解題思路
這題是樹的處理
我們可以用遞迴的方式進行比較
- 如果 root 是 null,回傳 true
- 如果左邊和右邊都是 null,回傳 true
- 如果左邊的值和右邊的值不同,回傳 false
- 遞迴比較
- 左邊 node 的左邊,和右邊 node 的右邊
- 左邊 node 的右邊,和右邊 node 的左邊
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 列表