From 81d4685e36603ec59e3e02d8243f60e660081541 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Fri, 20 May 2022 21:12:54 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200101.=E5=AF=B9=E7=A7=B0?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0101.对称二叉树.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index e4e232c8..97ca0685 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -725,5 +725,25 @@ func isSymmetric3(_ root: TreeNode?) -> Bool { } ``` +## Scala + +递归: +```scala +object Solution { + def isSymmetric(root: TreeNode): Boolean = { + if (root == null) return true // 如果等于空直接返回true + def compare(left: TreeNode, right: TreeNode): Boolean = { + if (left == null && right == null) return true // 如果左右都为空,则为true + if (left == null && right != null) return false // 如果左空右不空,不对称,返回false + if (left != null && right == null) return false // 如果左不空右空,不对称,返回false + // 如果左右的值相等,并且往下递归 + left.value == right.value && compare(left.left, right.right) && compare(left.right, right.left) + } + // 分别比较左子树和右子树 + compare(root.left, root.right) + } +} +``` + -----------------------