File tree Expand file tree Collapse file tree 2 files changed +68
-0
lines changed Expand file tree Collapse file tree 2 files changed +68
-0
lines changed Original file line number Diff line number Diff line change @@ -725,5 +725,25 @@ func isSymmetric3(_ root: TreeNode?) -> Bool {
725725}
726726```
727727
728+ ## Scala
729+
730+ 递归:
731+ ``` scala
732+ object Solution {
733+ def isSymmetric (root : TreeNode ): Boolean = {
734+ if (root == null ) return true // 如果等于空直接返回true
735+ def compare (left : TreeNode , right : TreeNode ): Boolean = {
736+ if (left == null && right == null ) return true // 如果左右都为空,则为true
737+ if (left == null && right != null ) return false // 如果左空右不空,不对称,返回false
738+ if (left != null && right == null ) return false // 如果左不空右空,不对称,返回false
739+ // 如果左右的值相等,并且往下递归
740+ left.value == right.value && compare(left.left, right.right) && compare(left.right, right.left)
741+ }
742+ // 分别比较左子树和右子树
743+ compare(root.left, root.right)
744+ }
745+ }
746+ ```
747+
728748-----------------------
729749<div align =" center " ><img src =https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width =500 > </img ></div >
Original file line number Diff line number Diff line change @@ -818,5 +818,53 @@ func invertTree(_ root: TreeNode?) -> TreeNode? {
818818}
819819```
820820
821+ ### Scala
822+
823+ 深度优先遍历(前序遍历):
824+ ``` scala
825+ object Solution {
826+ def invertTree (root : TreeNode ): TreeNode = {
827+ if (root == null ) return root
828+ // 递归
829+ def process (node : TreeNode ): Unit = {
830+ if (node == null ) return
831+ // 翻转节点
832+ val curNode = node.left
833+ node.left = node.right
834+ node.right = curNode
835+ process(node.left)
836+ process(node.right)
837+ }
838+ process(root)
839+ root
840+ }
841+ }
842+ ```
843+
844+ 广度优先遍历(层序遍历):
845+ ``` scala
846+ object Solution {
847+ import scala .collection .mutable
848+ def invertTree (root : TreeNode ): TreeNode = {
849+ if (root == null ) return root
850+ val queue = mutable.Queue [TreeNode ]()
851+ queue.enqueue(root)
852+ while (! queue.isEmpty) {
853+ val len = queue.size
854+ for (i <- 0 until len) {
855+ var curNode = queue.dequeue()
856+ if (curNode.left != null ) queue.enqueue(curNode.left)
857+ if (curNode.right != null ) queue.enqueue(curNode.right)
858+ // 翻转
859+ var tmpNode = curNode.left
860+ curNode.left = curNode.right
861+ curNode.right = tmpNode
862+ }
863+ }
864+ root
865+ }
866+ }
867+ ```
868+
821869-----------------------
822870<div align =" center " ><img src =https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width =500 > </img ></div >
You can’t perform that action at this time.
0 commit comments