mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加 0404.左叶子之和.md Scala版本
This commit is contained in:
@ -516,6 +516,44 @@ int sumOfLeftLeaves(struct TreeNode* root){
|
||||
}
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
**递归:**
|
||||
```scala
|
||||
object Solution {
|
||||
def sumOfLeftLeaves(root: TreeNode): Int = {
|
||||
if(root == null) return 0
|
||||
var midValue = 0
|
||||
if(root.left != null && root.left.left == null && root.left.right == null){
|
||||
midValue = root.left.value
|
||||
}
|
||||
// return关键字可以省略
|
||||
midValue + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**迭代:**
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def sumOfLeftLeaves(root: TreeNode): Int = {
|
||||
val stack = mutable.Stack[TreeNode]()
|
||||
if (root == null) return 0
|
||||
stack.push(root)
|
||||
var sum = 0
|
||||
while (!stack.isEmpty) {
|
||||
val curNode = stack.pop()
|
||||
if (curNode.left != null && curNode.left.left == null && curNode.left.right == null) {
|
||||
sum += curNode.left.value // 如果满足条件就累加
|
||||
}
|
||||
if (curNode.right != null) stack.push(curNode.right)
|
||||
if (curNode.left != null) stack.push(curNode.left)
|
||||
}
|
||||
sum
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<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