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 a69ee03

Browse files
committed
添加 0404.左叶子之和.md Scala版本
1 parent b78e750 commit a69ee03

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

‎problems/0404.左叶子之和.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -516,6 +516,44 @@ int sumOfLeftLeaves(struct TreeNode* root){
516516
}
517517
```
518518

519+
## Scala
520+
521+
**递归:**
522+
```scala
523+
object Solution {
524+
def sumOfLeftLeaves(root: TreeNode): Int = {
525+
if(root == null) return 0
526+
var midValue = 0
527+
if(root.left != null && root.left.left == null && root.left.right == null){
528+
midValue = root.left.value
529+
}
530+
// return关键字可以省略
531+
midValue + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right)
532+
}
533+
}
534+
```
535+
536+
**迭代:**
537+
```scala
538+
object Solution {
539+
import scala.collection.mutable
540+
def sumOfLeftLeaves(root: TreeNode): Int = {
541+
val stack = mutable.Stack[TreeNode]()
542+
if (root == null) return 0
543+
stack.push(root)
544+
var sum = 0
545+
while (!stack.isEmpty) {
546+
val curNode = stack.pop()
547+
if (curNode.left != null && curNode.left.left == null && curNode.left.right == null) {
548+
sum += curNode.left.value // 如果满足条件就累加
549+
}
550+
if (curNode.right != null) stack.push(curNode.right)
551+
if (curNode.left != null) stack.push(curNode.left)
552+
}
553+
sum
554+
}
555+
}
556+
```
519557

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

0 commit comments

Comments
(0)

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