mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge pull request #1745 from EnzoSeason/leetcode-101
Update 0101.对称二叉树.md
This commit is contained in:
@ -754,23 +754,77 @@ func isSymmetric3(_ root: TreeNode?) -> Bool {
|
||||
|
||||
## Scala
|
||||
|
||||
递归:
|
||||
> 递归:
|
||||
```scala
|
||||
object Solution {
|
||||
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
|
||||
if (left == null && right == null) true // 如果左右都为空,则为true
|
||||
else if (left == null && right != null) false // 如果左空右不空,不对称,返回false
|
||||
else if (left != null && right == null) false // 如果左不空右空,不对称,返回false
|
||||
// 如果左右的值相等,并且往下递归
|
||||
left.value == right.value && compare(left.left, right.right) && compare(left.right, right.left)
|
||||
else left.value == right.value && compare(left.left, right.right) && compare(left.right, right.left)
|
||||
}
|
||||
|
||||
// 分别比较左子树和右子树
|
||||
compare(root.left, root.right)
|
||||
}
|
||||
}
|
||||
```
|
||||
> 迭代 - 使用栈
|
||||
```scala
|
||||
object Solution {
|
||||
|
||||
import scala.collection.mutable
|
||||
|
||||
def isSymmetric(root: TreeNode): Boolean = {
|
||||
if (root == null) return true
|
||||
|
||||
val cache = mutable.Stack[(TreeNode, TreeNode)]((root.left, root.right))
|
||||
|
||||
while (cache.nonEmpty) {
|
||||
cache.pop() match {
|
||||
case (null, null) =>
|
||||
case (_, null) => return false
|
||||
case (null, _) => return false
|
||||
case (left, right) =>
|
||||
if (left.value != right.value) return false
|
||||
cache.push((left.left, right.right))
|
||||
cache.push((left.right, right.left))
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
```
|
||||
> 迭代 - 使用队列
|
||||
```scala
|
||||
object Solution {
|
||||
|
||||
import scala.collection.mutable
|
||||
|
||||
def isSymmetric(root: TreeNode): Boolean = {
|
||||
if (root == null) return true
|
||||
|
||||
val cache = mutable.Queue[(TreeNode, TreeNode)]((root.left, root.right))
|
||||
|
||||
while (cache.nonEmpty) {
|
||||
cache.dequeue() match {
|
||||
case (null, null) =>
|
||||
case (_, null) => return false
|
||||
case (null, _) => return false
|
||||
case (left, right) =>
|
||||
if (left.value != right.value) return false
|
||||
cache.enqueue((left.left, right.right))
|
||||
cache.enqueue((left.right, right.left))
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
|
Reference in New Issue
Block a user