From f604aea34c6632e20ad4ced37cb24c005420e574 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Tue, 8 Feb 2022 23:00:31 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880404.=E5=B7=A6?= =?UTF-8?q?=E5=8F=B6=E5=AD=90=E4=B9=8B=E5=92=8C.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0404.左叶子之和.md | 44 ++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md index 09272052..2b4df151 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -372,6 +372,50 @@ var sumOfLeftLeaves = function(root) { }; ``` +## TypeScript + +> 递归法 + +```typescript +function sumOfLeftLeaves(root: TreeNode | null): number { + if (root === null) return 0; + let midVal: number = 0; + if ( + root.left !== null && + root.left.left === null && + root.left.right === null + ) { + midVal = root.left.val; + } + let leftVal: number = sumOfLeftLeaves(root.left); + let rightVal: number = sumOfLeftLeaves(root.right); + return midVal + leftVal + rightVal; +}; +``` + +> 迭代法 + +```typescript +function sumOfLeftLeaves(root: TreeNode | null): number { + let helperStack: TreeNode[] = []; + let tempNode: TreeNode; + let sum: number = 0; + if (root !== null) helperStack.push(root); + while (helperStack.length > 0) { + tempNode = helperStack.pop()!; + if ( + tempNode.left !== null && + tempNode.left.left === null && + tempNode.left.right === null + ) { + sum += tempNode.left.val; + } + if (tempNode.right !== null) helperStack.push(tempNode.right); + if (tempNode.left !== null) helperStack.push(tempNode.left); + } + return sum; +}; +``` ## Swift