@@ -754,23 +754,77 @@ func isSymmetric3(_ root: TreeNode?) -> Bool {
754
754
755
755
## Scala
756
756
757
- 递归:
757
+ > 递归:
758
758
``` scala
759
- object Solution {
759
+ object Solution {
760
760
def isSymmetric (root : TreeNode ): Boolean = {
761
761
if (root == null ) return true // 如果等于空直接返回true
762
+
762
763
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
766
767
// 如果左右的值相等,并且往下递归
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)
768
769
}
770
+
769
771
// 分别比较左子树和右子树
770
772
compare(root.left, root.right)
771
773
}
772
774
}
773
775
```
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
+ ```
774
828
775
829
<p align =" center " >
776
830
<a href =" https://programmercarl.com/other/kstar.html " target =" _blank " >
0 commit comments