File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -516,6 +516,44 @@ int sumOfLeftLeaves(struct TreeNode* root){
516
516
}
517
517
```
518
518
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
+ ```
519
557
520
558
-----------------------
521
559
<div align =" center " ><img src =https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width =500 > </img ></div >
You can’t perform that action at this time.
0 commit comments