From e4f674c61e71a7b33ec97e22acc6b7a44e075b6e Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Tue, 1 Feb 2022 20:04:51 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880111.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F=E6=B7=B1=E5=BA=A6?= =?UTF-8?q?.md=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/0111.二叉树的最小深度.md | 38 +++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index a439322a..224caa5e 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -404,6 +404,44 @@ var minDepth = function(root) { }; ``` +## TypeScript + +> 递归法 + +```typescript +function minDepth(root: TreeNode | null): number { + if (root === null) return 0; + if (root.left !== null && root.right === null) { + return 1 + minDepth(root.left); + } + if (root.left === null && root.right !== null) { + return 1 + minDepth(root.right); + } + return 1 + Math.min(minDepth(root.left), minDepth(root.right)); +} +``` + +> 迭代法 + +```typescript +function minDepth(root: TreeNode | null): number { + let helperQueue: TreeNode[] = []; + let resMin: number = 0; + let tempNode: TreeNode; + if (root !== null) helperQueue.push(root); + while (helperQueue.length > 0) { + resMin++; + for (let i = 0, length = helperQueue.length; i < length; i++) { + tempNode = helperQueue.shift()!; + if (tempNode.left === null && tempNode.right === null) return resMin; + if (tempNode.left !== null) helperQueue.push(tempNode.left); + if (tempNode.right !== null) helperQueue.push(tempNode.right); + } + } + return resMin; +}; +``` + ## Swift > 递归