File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * function TreeNode(val) {
4
+ * this.val = val;
5
+ * this.left = this.right = null;
6
+ * }
7
+ */
8
+ /**
9
+ * @param {TreeNode } root
10
+ * @return {number }
11
+ * https://leetcode.com/problems/maximum-depth-of-binary-tree/
12
+ */
13
+ // 广度优先搜索
14
+ var maxDepth = function ( root ) {
15
+ if ( ! root ) {
16
+ return 0 ;
17
+ }
18
+
19
+ let queue = [ ] ;
20
+ let level = [ root ] ;
21
+ let depth = 0 ;
22
+
23
+ while ( level . length ) {
24
+ depth ++ ;
25
+
26
+ while ( level . length ) {
27
+ let node = level . shift ( ) ;
28
+ if ( node . left ) {
29
+ queue . push ( node . left ) ;
30
+ }
31
+ if ( node . right ) {
32
+ queue . push ( node . right ) ;
33
+ }
34
+ }
35
+ level = queue ;
36
+ queue = [ ] ;
37
+ }
38
+
39
+ return depth ;
40
+ } ;
41
+
42
+ // DFS 深度优先搜索 递归形式
43
+ var maxDepth = function ( root ) {
44
+ if ( ! root ) {
45
+ return 0 ;
46
+ }
47
+ return Math . max ( maxDepth ( root . left ) + 1 , maxDepth ( root . right ) + 1 ) ;
48
+ } ;
49
+
50
+ // DFS 深度优先搜索 非递归形式
51
+ var maxDepth = function ( root ) {
52
+ if ( ! root ) {
53
+ return 0 ;
54
+ }
55
+ } ;
You can’t perform that action at this time.
0 commit comments