Skip to content

Commit 30550b0

Browse files
authored
Update 0101.对称二叉树.md
1 parent fbc50c0 commit 30550b0

File tree

1 file changed

+60
-6
lines changed

1 file changed

+60
-6
lines changed

problems/0101.对称二叉树.md

Lines changed: 60 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -754,23 +754,77 @@ func isSymmetric3(_ root: TreeNode?) -> Bool {
754754

755755
## Scala
756756

757-
递归:
757+
> 递归:
758758
```scala
759-
object Solution {
759+
object Solution {
760760
def isSymmetric(root: TreeNode): Boolean = {
761761
if (root == null) return true // 如果等于空直接返回true
762+
762763
def compare(left: TreeNode, right: TreeNode): Boolean = {
763-
if (left == null && right == null) return true // 如果左右都为空,则为true
764-
if (left == null && right != null) return false // 如果左空右不空,不对称,返回false
765-
if (left != null && right == null) return false // 如果左不空右空,不对称,返回false
764+
if (left == null && right == null) true // 如果左右都为空,则为true
765+
else if (left == null && right != null) false // 如果左空右不空,不对称,返回false
766+
else if (left != null && right == null) false // 如果左不空右空,不对称,返回false
766767
// 如果左右的值相等,并且往下递归
767-
left.value == right.value && compare(left.left, right.right) && compare(left.right, right.left)
768+
else left.value == right.value && compare(left.left, right.right) && compare(left.right, right.left)
768769
}
770+
769771
// 分别比较左子树和右子树
770772
compare(root.left, root.right)
771773
}
772774
}
773775
```
776+
> 迭代 - 使用栈
777+
```scala
778+
object Solution {
779+
780+
import scala.collection.mutable
781+
782+
def isSymmetric(root: TreeNode): Boolean = {
783+
if (root == null) return true
784+
785+
val cache = mutable.Stack[(TreeNode, TreeNode)]((root.left, root.right))
786+
787+
while (cache.nonEmpty) {
788+
cache.pop() match {
789+
case (null, null) =>
790+
case (_, null) => return false
791+
case (null, _) => return false
792+
case (left, right) =>
793+
if (left.value != right.value) return false
794+
cache.push((left.left, right.right))
795+
cache.push((left.right, right.left))
796+
}
797+
}
798+
true
799+
}
800+
}
801+
```
802+
> 迭代 - 使用队列
803+
```scala
804+
object Solution {
805+
806+
import scala.collection.mutable
807+
808+
def isSymmetric(root: TreeNode): Boolean = {
809+
if (root == null) return true
810+
811+
val cache = mutable.Queue[(TreeNode, TreeNode)]((root.left, root.right))
812+
813+
while (cache.nonEmpty) {
814+
cache.dequeue() match {
815+
case (null, null) =>
816+
case (_, null) => return false
817+
case (null, _) => return false
818+
case (left, right) =>
819+
if (left.value != right.value) return false
820+
cache.enqueue((left.left, right.right))
821+
cache.enqueue((left.right, right.left))
822+
}
823+
}
824+
true
825+
}
826+
}
827+
```
774828

775829
<p align="center">
776830
<a href="https://programmercarl.com/other/kstar.html" target="_blank">

0 commit comments

Comments
 (0)