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+ * TC: O(N)
3+ * 모든 노드를 순회합니다.
4+ *
5+ * SC: O(N)
6+ * 노드의 수에 비례해서 queue의 길이가 증가됩니다.
7+ *
8+ * N: count of tree node
9+ */
10+
11+ /**
12+ * Definition for a binary tree node.
13+ * function TreeNode(val, left, right) {
14+ * this.val = (val===undefined ? 0 : val)
15+ * this.left = (left===undefined ? null : left)
16+ * this.right = (right===undefined ? null : right)
17+ * }
18+ */
19+ /**
20+ * @param {TreeNode } root
21+ * @return {number }
22+ */
23+ var maxDepth = function ( root ) {
24+ let maximumDepth = 0 ;
25+
26+ const queue = [ [ root , 1 ] ] ;
27+ while ( queue . length > 0 ) {
28+ const [ current , depth ] = queue . shift ( ) ;
29+
30+ if ( current === null ) {
31+ break ;
32+ }
33+
34+ maximumDepth = Math . max ( maximumDepth , depth ) ;
35+
36+ if ( current . left ) {
37+ queue . push ( [ current . left , depth + 1 ] ) ;
38+ }
39+
40+ if ( current . right ) {
41+ queue . push ( [ current . right , depth + 1 ] ) ;
42+ }
43+ }
44+
45+ return maximumDepth ;
46+ } ;
You can’t perform that action at this time.
0 commit comments