File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
binary-tree-level-order-traversal Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * 문제 설명
3+ * - 이진 트리의 레벨 순서 순회 문제
4+ *
5+ * 아이디어
6+ * 1) BFS 레벨 순서별로 큐에 넣어서 탐색하며 결과를 반환
7+ *
8+ */
9+ /**
10+ * Definition for a binary tree node.
11+ * class TreeNode {
12+ * val: number
13+ * left: TreeNode | null
14+ * right: TreeNode | null
15+ * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
16+ * this.val = (val===undefined ? 0 : val)
17+ * this.left = (left===undefined ? null : left)
18+ * this.right = (right===undefined ? null : right)
19+ * }
20+ * }
21+ */
22+
23+ function levelOrder ( root : TreeNode | null ) : number [ ] [ ] {
24+ if ( ! root ) return [ ] ;
25+
26+ const queue : TreeNode [ ] = [ root ] ;
27+ const result : number [ ] [ ] = [ ] ;
28+
29+ while ( queue . length ) {
30+ const levelSize = queue . length ;
31+ const currentLevel : number [ ] = [ ] ;
32+ for ( let i = 0 ; i < levelSize ; i ++ ) {
33+ const node = queue . shift ( ) ! ;
34+ currentLevel . push ( node . val ) ;
35+
36+ if ( node . left ) queue . push ( node . left ) ;
37+ if ( node . right ) queue . push ( node . right ) ;
38+ }
39+
40+ result . push ( currentLevel ) ;
41+ }
42+ return result ;
43+ }
You can’t perform that action at this time.
0 commit comments