Skip to content

Commit 17a2ea3

Browse files
committed
添加 0513.找树左下角的值.md Scala版本
1 parent a69ee03 commit 17a2ea3

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

problems/0513.找树左下角的值.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -546,7 +546,50 @@ func findBottomLeftValue(_ root: TreeNode?) -> Int {
546546
}
547547
```
548548

549+
## Scala
550+
551+
递归版本:
552+
```scala
553+
object Solution {
554+
def findBottomLeftValue(root: TreeNode): Int = {
555+
var maxLeftValue = 0
556+
var maxLen = Int.MinValue
557+
// 递归方法
558+
def traversal(node: TreeNode, leftLen: Int): Unit = {
559+
// 如果左右都为空并且当前深度大于最大深度,记录最左节点的值
560+
if (node.left == null && node.right == null && leftLen > maxLen) {
561+
maxLen = leftLen
562+
maxLeftValue = node.value
563+
}
564+
if (node.left != null) traversal(node.left, leftLen + 1)
565+
if (node.right != null) traversal(node.right, leftLen + 1)
566+
}
567+
traversal(root, 0) // 调用方法
568+
maxLeftValue // return关键字可以省略
569+
}
570+
}
571+
```
549572

573+
层序遍历:
574+
```scala
575+
import scala.collection.mutable
576+
577+
def findBottomLeftValue(root: TreeNode): Int = {
578+
val queue = mutable.Queue[TreeNode]()
579+
queue.enqueue(root)
580+
var res = 0 // 记录每层最左侧结果
581+
while (!queue.isEmpty) {
582+
val len = queue.size
583+
for (i <- 0 until len) {
584+
val curNode = queue.dequeue()
585+
if (i == 0) res = curNode.value // 记录最最左侧的节点
586+
if (curNode.left != null) queue.enqueue(curNode.left)
587+
if (curNode.right != null) queue.enqueue(curNode.right)
588+
}
589+
}
590+
res // 最终返回结果,return关键字可以省略
591+
}
592+
```
550593

551594
-----------------------
552595
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
 (0)