mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加 0257.二叉树的所有路径.md Scala版本
This commit is contained in:
@ -702,5 +702,35 @@ func binaryTreePaths(_ root: TreeNode?) -> [String] {
|
||||
}
|
||||
```
|
||||
|
||||
Scala:
|
||||
|
||||
递归:
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable.ListBuffer
|
||||
def binaryTreePaths(root: TreeNode): List[String] = {
|
||||
val res = ListBuffer[String]()
|
||||
def traversal(curNode: TreeNode, path: ListBuffer[Int]): Unit = {
|
||||
path.append(curNode.value)
|
||||
if (curNode.left == null && curNode.right == null) {
|
||||
res.append(path.mkString("->")) // mkString函数: 将数组的所有值按照指定字符串拼接
|
||||
return // 处理完可以直接return
|
||||
}
|
||||
|
||||
if (curNode.left != null) {
|
||||
traversal(curNode.left, path)
|
||||
path.remove(path.size - 1)
|
||||
}
|
||||
if (curNode.right != null) {
|
||||
traversal(curNode.right, path)
|
||||
path.remove(path.size - 1)
|
||||
}
|
||||
}
|
||||
traversal(root, ListBuffer[Int]())
|
||||
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