Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 45a3c91

Browse files
committed
添加 0257.二叉树的所有路径.md Scala版本
1 parent f83d5ed commit 45a3c91

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

‎problems/0257.二叉树的所有路径.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -702,5 +702,35 @@ func binaryTreePaths(_ root: TreeNode?) -> [String] {
702702
}
703703
```
704704

705+
Scala:
706+
707+
递归:
708+
```scala
709+
object Solution {
710+
import scala.collection.mutable.ListBuffer
711+
def binaryTreePaths(root: TreeNode): List[String] = {
712+
val res = ListBuffer[String]()
713+
def traversal(curNode: TreeNode, path: ListBuffer[Int]): Unit = {
714+
path.append(curNode.value)
715+
if (curNode.left == null && curNode.right == null) {
716+
res.append(path.mkString("->")) // mkString函数: 将数组的所有值按照指定字符串拼接
717+
return // 处理完可以直接return
718+
}
719+
720+
if (curNode.left != null) {
721+
traversal(curNode.left, path)
722+
path.remove(path.size - 1)
723+
}
724+
if (curNode.right != null) {
725+
traversal(curNode.right, path)
726+
path.remove(path.size - 1)
727+
}
728+
}
729+
traversal(root, ListBuffer[Int]())
730+
res.toList
731+
}
732+
}
733+
```
734+
705735
-----------------------
706736
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /