Merge pull request #656 from martisss/master

修改  104. 二叉树最大深度  的重复代码;增加  559. N叉树最大深度的递归与层序遍历   的javascript实现
This commit is contained in:
程序员Carl
2021-08-26 15:25:27 +08:00
committed by GitHub

View File

@ -505,21 +505,51 @@ var maxdepth = function(root) {
二叉树最大深度层级遍历 二叉树最大深度层级遍历
```javascript ```javascript
var maxdepth = function(root) { var maxDepth = function(root) {
//使用递归的方法 递归三部曲 if(!root) return 0
//1. 确定递归函数的参数和返回值 let count = 0
const getdepth=function(node){ const queue = [root]
//2. 确定终止条件 while(queue.length) {
if(node===null){ let size = queue.length
return 0; /* 层数+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
}; };
``` ```