Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update 0101.对称二叉树.md #1745

Merged
merged 1 commit into from
Nov 22, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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