File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
binary-tree-level-order-traversal Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @description
3
+ * 동일한 depth를 방문해야하므로 bfs 및 트리 순회
4
+ *
5
+ * n = length of node of root
6
+ * time complexity: O(n)
7
+ * space complexity: O(n)
8
+ */
9
+ var levelOrder = function ( root ) {
10
+ if ( ! root ) return [ ] ;
11
+
12
+ const answer = [ ] ;
13
+ const queue = [ root ] ;
14
+ let queueCurrentIndex = 0 ;
15
+
16
+ while ( queue . length > queueCurrentIndex ) {
17
+ answer . push ( [ ] ) ;
18
+ const answerLastIndex = answer . length - 1 ;
19
+ const depthEndIndex = queue . length ;
20
+
21
+ while ( depthEndIndex !== queueCurrentIndex ) {
22
+ const tree = queue [ queueCurrentIndex ++ ] ;
23
+
24
+ answer [ answerLastIndex ] . push ( tree . val ) ;
25
+ if ( tree . left ) queue . push ( tree . left ) ;
26
+ if ( tree . right ) queue . push ( tree . right ) ;
27
+ }
28
+ }
29
+
30
+ return answer ;
31
+ } ;
You can’t perform that action at this time.
0 commit comments