From 4ed65b50d174a3d9f89d0352ee30da95fcecece9 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Wed, 9 Feb 2022 22:45:31 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880513.=E6=89=BE?= =?UTF-8?q?=E6=A0=91=E5=B7=A6=E4=B8=8B=E8=A7=92=E7=9A=84=E5=80=BC.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0513.找树左下角的值.md | 45 ++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/problems/0513.找树左下角的值.md b/problems/0513.找树左下角的值.md index 84ed3932..12c62c70 100644 --- a/problems/0513.找树左下角的值.md +++ b/problems/0513.找树左下角的值.md @@ -433,6 +433,51 @@ var findBottomLeftValue = function(root) { }; ``` +## TypeScript + +> 递归法: + +```typescript +function findBottomLeftValue(root: TreeNode | null): number { + function recur(root: TreeNode, depth: number): void { + if (root.left === null && root.right === null) { + if (depth > maxDepth) { + maxDepth = depth; + resVal = root.val; + } + return; + } + if (root.left !== null) recur(root.left, depth + 1); + if (root.right !== null) recur(root.right, depth + 1); + } + let maxDepth: number = 0; + let resVal: number = 0; + if (root === null) return resVal; + recur(root, 1); + return resVal; +}; +``` + +> 迭代法: + +```typescript +function findBottomLeftValue(root: TreeNode | null): number { + let helperQueue: TreeNode[] = []; + if (root !== null) helperQueue.push(root); + let resVal: number = 0; + let tempNode: TreeNode; + while (helperQueue.length > 0) { + resVal = helperQueue[0].val; + for (let i = 0, length = helperQueue.length; i < length; i++) { + tempNode = helperQueue.shift()!; + if (tempNode.left !== null) helperQueue.push(tempNode.left); + if (tempNode.right !== null) helperQueue.push(tempNode.right); + } + } + return resVal; +}; +``` + ## Swift 递归版本: