File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
binary-tree-level-order-traversal Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * 2차
3+ * 각 level의 node 수만큼 끊어서 순회하기
4+ *
5+ * TC: O(N)
6+ * SC: O(N)
7+ * N: total of nodes
8+ */
9+
10+ /**
11+ * Definition for a binary tree node.
12+ * function TreeNode(val, left, right) {
13+ * this.val = (val===undefined ? 0 : val)
14+ * this.left = (left===undefined ? null : left)
15+ * this.right = (right===undefined ? null : right)
16+ * }
17+ */
18+ /**
19+ * @param {TreeNode } root
20+ * @return {number[][] }
21+ */
22+ var levelOrder = function ( root ) {
23+ if ( ! root ) {
24+ return [ ] ;
25+ }
26+
27+ const result = [ ] ;
28+ const queue = [ root ] ;
29+
30+ while ( queue . length > 0 ) {
31+ const level = queue . length ;
32+ const currentLevelValList = [ ] ;
33+
34+ for ( let i = 0 ; i < level ; i ++ ) {
35+ const current = queue . shift ( ) ;
36+
37+ currentLevelValList . push ( current . val ) ;
38+
39+ if ( current . left ) {
40+ queue . push ( current . left ) ;
41+ }
42+
43+ if ( current . right ) {
44+ queue . push ( current . right ) ;
45+ }
46+ }
47+
48+ result . push ( currentLevelValList ) ;
49+ }
50+
51+ return result ;
52+ } ;
53+
154/**
255 * 1차
56+ * level과 노드를 queue에 추가해서 정답만들기
357 *
458 * TC: O(N)
559 * SC: O(N)
You can’t perform that action at this time.
0 commit comments