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] =?UTF-8?q?=E5=88=A0=E9=99=A4=E9=87=8D=E5=A4=8D=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=EF=BC=8C=E5=A2=9E=E5=8A=A0N=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6=E7=9A=84=E9=80=92=E5=BD=92?= =?UTF-8?q?=E4=B8=8E=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86=E5=AE=9E=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 }; ```