From a69ee03b3eea09f7e2bb113b631462eadd313482 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Tue, 24 May 2022 18:59:17 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200404.=E5=B7=A6=E5=8F=B6?= =?UTF-8?q?=E5=AD=90=E4=B9=8B=E5=92=8C.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0404.左叶子之和.md | 38 ++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md index d7fd629e..78fc58f3 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -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 + } +} +``` -----------------------