File tree Expand file tree Collapse file tree 1 file changed +43
-13
lines changed Expand file tree Collapse file tree 1 file changed +43
-13
lines changed Original file line number Diff line number Diff line change @@ -505,21 +505,51 @@ var maxdepth = function(root) {
505
505
506
506
二叉树最大深度层级遍历
507
507
``` 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 ])
515
550
}
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;
521
551
}
522
- return getDepth (root);
552
+ return count
523
553
};
524
554
```
525
555
You can’t perform that action at this time.
0 commit comments