mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Merge pull request #1369 from wzqwtt/tree06
添加(0226.翻转二叉树、0101.对称二叉树)Scala版本
This commit is contained in:
@ -725,5 +725,25 @@ func isSymmetric3(_ root: TreeNode?) -> Bool {
|
||||
}
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
递归:
|
||||
```scala
|
||||
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
|
||||
// 如果左右的值相等,并且往下递归
|
||||
left.value == right.value && compare(left.left, right.right) && compare(left.right, right.left)
|
||||
}
|
||||
// 分别比较左子树和右子树
|
||||
compare(root.left, root.right)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -818,5 +818,53 @@ func invertTree(_ root: TreeNode?) -> TreeNode? {
|
||||
}
|
||||
```
|
||||
|
||||
### Scala
|
||||
|
||||
深度优先遍历(前序遍历):
|
||||
```scala
|
||||
object Solution {
|
||||
def invertTree(root: TreeNode): TreeNode = {
|
||||
if (root == null) return root
|
||||
// 递归
|
||||
def process(node: TreeNode): Unit = {
|
||||
if (node == null) return
|
||||
// 翻转节点
|
||||
val curNode = node.left
|
||||
node.left = node.right
|
||||
node.right = curNode
|
||||
process(node.left)
|
||||
process(node.right)
|
||||
}
|
||||
process(root)
|
||||
root
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
广度优先遍历(层序遍历):
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def invertTree(root: TreeNode): TreeNode = {
|
||||
if (root == null) return root
|
||||
val queue = mutable.Queue[TreeNode]()
|
||||
queue.enqueue(root)
|
||||
while (!queue.isEmpty) {
|
||||
val len = queue.size
|
||||
for (i <- 0 until len) {
|
||||
var curNode = queue.dequeue()
|
||||
if (curNode.left != null) queue.enqueue(curNode.left)
|
||||
if (curNode.right != null) queue.enqueue(curNode.right)
|
||||
// 翻转
|
||||
var tmpNode = curNode.left
|
||||
curNode.left = curNode.right
|
||||
curNode.right = tmpNode
|
||||
}
|
||||
}
|
||||
root
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user