From 5d8a0b091ced561f0538934245f3e5a64e6ea9f2 Mon Sep 17 00:00:00 2001 From: martisss <2466632626@qq.com> Date: Thu, 26 Aug 2021 09:47:05 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E5=88=A0=E9=99=A4=E9=87=8D=E5=A4=8D?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=EF=BC=8C=E5=A2=9E=E5=8A=A0N=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6=E7=9A=84=E9=80=92?= =?UTF-8?q?=E5=BD=92=E4=B8=8E=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0104.二叉树的最大深度.md | 56 +++++++++++++++++------ 1 file changed, 43 insertions(+), 13 deletions(-) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index d086686d..7adb8bb7 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -505,21 +505,51 @@ var maxdepth = function(root) { 二叉树最大深度层级遍历 ```javascript -var maxdepth = function(root) { - //使用递归的方法 递归三部曲 - //1. 确定递归函数的参数和返回值 - const getdepth=function(node){ - //2. 确定终止条件 - if(node===null){ - return 0; +var maxDepth = function(root) { + if(!root) return 0 + let count = 0 + const queue = [root] + while(queue.length) { + let size = queue.length + /* 层数+1 */ + count++ + while(size--) { + let node = queue.shift(); + node.left && queue.push(node.left); + node.right && queue.push(node.right); } - //3. 确定单层逻辑 - let leftdepth=getdepth(node.left); - let rightdepth=getdepth(node.right); - let depth=1+math.max(leftdepth,rightdepth); - return depth; } - return getDepth(root); + return count +}; +``` + +N叉树的最大深度 递归写法 +```js +var maxDepth = function(root) { + if(!root) return 0 + let depth = 0 + for(let node of root.children) { + depth = Math.max(depth, maxDepth(node)) + } + return depth + 1 +} +``` + +N叉树的最大深度 层序遍历 +```js +var maxDepth = function(root) { + if(!root) return 0 + let count = 0 + let queue = [root] + while(queue.length) { + let size = queue.length + count++ + while(size--) { + let node = queue.shift() + node && (queue = [...queue, ...node.children]) + } + } + return count }; ``` From e419a5f90815cf233a6e91ea51c7c23c005e4d22 Mon Sep 17 00:00:00 2001 From: xsduan98 Date: Thu, 26 Aug 2021 10:29:54 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E7=AC=AC51=E9=A2=98.N=E7=9A=87=E5=90=8E=20?= =?UTF-8?q?=E4=BF=AE=E6=94=B9Java=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0051.N皇后.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0051.N皇后.md b/problems/0051.N皇后.md index 5404b620..9cc84cf8 100644 --- a/problems/0051.N皇后.md +++ b/problems/0051.N皇后.md @@ -332,7 +332,7 @@ class Solution { public boolean isValid(int row, int col, int n, char[][] chessboard) { // 检查列 - for (int i=0; i