From 41272638670e6da93171dfce8af63d5da42d4e36 Mon Sep 17 00:00:00 2001 From: "qingyi.liu" Date: Tue, 18 May 2021 22:51:51 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0111.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F=E6=B7=B1=E5=BA=A6=20JavaSc?= =?UTF-8?q?ript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0111.二叉树的最小深度.md | 47 +++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index 01b6c89c..5605e13d 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -302,6 +302,53 @@ class Solution: Go: +JavaScript: + +递归法: + +```javascript +/** + * @param {TreeNode} root + * @return {number} + */ +var minDepth1 = function(root) { + if(!root) return 0; + // 到叶子节点 返回 1 + if(!root.left && !root.right) return 1; + // 只有右节点时 递归右节点 + if(!root.left) return 1 + minDepth(root.right);、 + // 只有左节点时 递归左节点 + if(!root.right) return 1 + minDepth(root.left); + return Math.min(minDepth(root.left), minDepth(root.right)) + 1; +}; +``` + +迭代法: + +```javascript +/** +* @param {TreeNode} root +* @return {number} +*/ +var minDepth = function(root) { + if(!root) return 0; + const queue = [root]; + let dep = 0; + while(true) { + let size = queue.length; + dep++; + while(size--){ + const node = queue.shift(); + // 到第一个叶子节点 返回 当前深度 + if(!node.left && !node.right) return dep; + node.left && queue.push(node.left); + node.right && queue.push(node.right); + } + } +}; +``` + + -----------------------