File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +46
-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, left, right) {
4
+ * this.val = (val===undefined ? 0 : val)
5
+ * this.left = (left===undefined ? null : left)
6
+ * this.right = (right===undefined ? null : right)
7
+ * }
8
+ */
9
+ /**
10
+ * @param {TreeNode } root
11
+ * @return {number }
12
+ */
13
+ var maxDepth = function ( root ) {
14
+ // Check root is null or not
15
+ if ( root === null ) {
16
+ return 0 ;
17
+ }
18
+ // Make queue array to store root and depth variable
19
+ let queue = [ root ] ;
20
+ let depth = 0 ;
21
+ // Iterate until there is an element inside of queue
22
+ while ( queue . length > 0 ) {
23
+ // Record level size to avoid fault size measuring
24
+ let levelSize = queue . length ;
25
+
26
+ for ( let i = 0 ; i < levelSize ; i ++ ) {
27
+ // Grasp first element from the queue
28
+ const node = queue . shift ( ) ;
29
+ // Push the left node into the queue
30
+ if ( node . left ) {
31
+ queue . push ( node . left ) ;
32
+ }
33
+ // Push the right node into the queue
34
+ if ( node . right ) {
35
+ queue . push ( node . right ) ;
36
+ }
37
+ }
38
+ // Increase depth value
39
+ depth ++ ;
40
+ }
41
+
42
+ return depth ;
43
+ } ;
44
+
45
+ // TC: O(n)
46
+ // SC: O(n)
You can’t perform that action at this time.
0 commit comments