Skip to content

Commit

Permalink
Merge pull request #1745 from EnzoSeason/leetcode-101
Browse files Browse the repository at this point in the history
Update 0101.对称二叉树.md
  • Loading branch information
youngyangyang04 authored Nov 22, 2022
2 parents b7d29cb + 30550b0 commit 2224f82
Showing 1 changed file with 60 additions and 6 deletions.
66 changes: 60 additions & 6 deletions problems/0101.对称二叉树.md
Original file line number Diff line number Diff line change
Expand Up @@ -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">
Expand Down

0 comments on commit 2224f82

Please sign in to comment.