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 }; ```