File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed
binary-tree-level-order-traversal Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * 1차
3+ *
4+ * TC: O(N)
5+ * SC: O(N)
6+ * N: total of nodes
7+ */
8+
9+ /**
10+ * Definition for a binary tree node.
11+ * function TreeNode(val, left, right) {
12+ * this.val = (val===undefined ? 0 : val)
13+ * this.left = (left===undefined ? null : left)
14+ * this.right = (right===undefined ? null : right)
15+ * }
16+ */
17+ /**
18+ * @param {TreeNode } root
19+ * @return {number[][] }
20+ */
21+ var levelOrder = function ( root ) {
22+ const result = [ ] ;
23+
24+ const queue = [
25+ {
26+ level : 0 ,
27+ current : root ,
28+ } ,
29+ ] ;
30+
31+ while ( queue . length > 0 ) {
32+ const { level, current } = queue . shift ( ) ;
33+
34+ if ( ! current ) {
35+ continue ;
36+ }
37+
38+ if ( result [ level ] ) {
39+ result [ level ] . push ( current . val ) ;
40+ } else {
41+ result [ level ] = [ current . val ] ;
42+ }
43+
44+ if ( current . left ) {
45+ queue . push ( {
46+ level : level + 1 ,
47+ current : current . left ,
48+ } ) ;
49+ }
50+
51+ if ( current . right ) {
52+ queue . push ( {
53+ level : level + 1 ,
54+ current : current . right ,
55+ } ) ;
56+ }
57+ }
58+
59+ return result ;
60+ } ;
You can’t perform that action at this time.
0 commit comments