mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 二叉树的递归遍历.md Scala版本
This commit is contained in:
@ -470,5 +470,56 @@ func postorder(_ root: TreeNode?, res: inout [Int]) {
|
||||
res.append(root!.val)
|
||||
}
|
||||
```
|
||||
Scala: 前序遍历:(144.二叉树的前序遍历)
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable.ListBuffer
|
||||
def preorderTraversal(root: TreeNode): List[Int] = {
|
||||
val res = ListBuffer[Int]()
|
||||
def traversal(curNode: TreeNode): Unit = {
|
||||
if(curNode == null) return
|
||||
res.append(curNode.value)
|
||||
traversal(curNode.left)
|
||||
traversal(curNode.right)
|
||||
}
|
||||
traversal(root)
|
||||
res.toList
|
||||
}
|
||||
}
|
||||
```
|
||||
中序遍历:(94. 二叉树的中序遍历)
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable.ListBuffer
|
||||
def inorderTraversal(root: TreeNode): List[Int] = {
|
||||
val res = ListBuffer[Int]()
|
||||
def traversal(curNode: TreeNode): Unit = {
|
||||
if(curNode == null) return
|
||||
traversal(curNode.left)
|
||||
res.append(curNode.value)
|
||||
traversal(curNode.right)
|
||||
}
|
||||
traversal(root)
|
||||
res.toList
|
||||
}
|
||||
}
|
||||
```
|
||||
后序遍历:(145. 二叉树的后序遍历)
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable.ListBuffer
|
||||
def postorderTraversal(root: TreeNode): List[Int] = {
|
||||
val res = ListBuffer[Int]()
|
||||
def traversal(curNode: TreeNode): Unit = {
|
||||
if (curNode == null) return
|
||||
traversal(curNode.left)
|
||||
traversal(curNode.right)
|
||||
res.append(curNode.value)
|
||||
}
|
||||
traversal(root)
|
||||
res.toList
|
||||
}
|
||||
}
|
||||
```
|
||||
-----------------------
|
||||
<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