Skip to content

Commit 5b31add

Browse files
Merge pull request youngyangyang04#656 from martisss/master
修改 104. 二叉树最大深度 的重复代码;增加 559. N叉树最大深度的递归与层序遍历 的javascript实现
2 parents c8149ce + 5d8a0b0 commit 5b31add

File tree

1 file changed

+43
-13
lines changed

1 file changed

+43
-13
lines changed

problems/0104.二叉树的最大深度.md

Lines changed: 43 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -505,21 +505,51 @@ var maxdepth = function(root) {
505505

506506
二叉树最大深度层级遍历
507507
```javascript
508-
var maxdepth = function(root) {
509-
//使用递归的方法 递归三部曲
510-
//1. 确定递归函数的参数和返回值
511-
const getdepth=function(node){
512-
//2. 确定终止条件
513-
if(node===null){
514-
return 0;
508+
var maxDepth = function(root) {
509+
if(!root) return 0
510+
let count = 0
511+
const queue = [root]
512+
while(queue.length) {
513+
let size = queue.length
514+
/* 层数+1 */
515+
count++
516+
while(size--) {
517+
let node = queue.shift();
518+
node.left && queue.push(node.left);
519+
node.right && queue.push(node.right);
520+
}
521+
}
522+
return count
523+
};
524+
```
525+
526+
N叉树的最大深度 递归写法
527+
```js
528+
var maxDepth = function(root) {
529+
if(!root) return 0
530+
let depth = 0
531+
for(let node of root.children) {
532+
depth = Math.max(depth, maxDepth(node))
533+
}
534+
return depth + 1
535+
}
536+
```
537+
538+
N叉树的最大深度 层序遍历
539+
```js
540+
var maxDepth = function(root) {
541+
if(!root) return 0
542+
let count = 0
543+
let queue = [root]
544+
while(queue.length) {
545+
let size = queue.length
546+
count++
547+
while(size--) {
548+
let node = queue.shift()
549+
node && (queue = [...queue, ...node.children])
515550
}
516-
//3. 确定单层逻辑
517-
let leftdepth=getdepth(node.left);
518-
let rightdepth=getdepth(node.right);
519-
let depth=1+math.max(leftdepth,rightdepth);
520-
return depth;
521551
}
522-
return getDepth(root);
552+
return count
523553
};
524554
```
525555

0 commit comments

Comments
 (0)