File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
binary-tree-level-order-traversal Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * function TreeNode(val, left, right) {
4
+ * this.val = (val===undefined ? 0 : val)
5
+ * this.left = (left===undefined ? null : left)
6
+ * this.right = (right===undefined ? null : right)
7
+ * }
8
+ */
9
+ /**
10
+ * @param {TreeNode } root
11
+ * @return {number[][] }
12
+ */
13
+ var levelOrder = function ( root ) {
14
+ if ( ! root ) {
15
+ return [ ] ;
16
+ }
17
+
18
+ const queue = [ root ] ;
19
+ const answer = [ ] ;
20
+
21
+ while ( queue . length > 0 ) {
22
+ const values = [ ] ;
23
+
24
+ const currentQueueLen = queue . length ;
25
+
26
+ for ( let i = 0 ; i < currentQueueLen ; i ++ ) {
27
+ const head = queue . shift ( ) ;
28
+
29
+ values . push ( head . val ) ;
30
+
31
+ head . left && queue . push ( head . left ) ;
32
+ head . right && queue . push ( head . right ) ;
33
+ }
34
+
35
+ answer . push ( values ) ;
36
+ }
37
+
38
+ return answer ;
39
+ } ;
40
+
41
+ // ์๊ฐ๋ณต์ก๋ O(n) -> ๋ชจ๋ ๋
ธ๋๋ฅผ ํ๋ฒ์ฉ ๋๋น์ฐ์ ํ์์ผ๋ก ๋ฐฉ๋ฌธํ๋ฏ๋ก
42
+ // ๊ณต๊ฐ๋ณต์ก๋ O(n) -> ํ์ ๋ชจ๋ ๋
ธ๋์ ๊ฐ์ ์ ์ฅํ๋ฏ๋ก
You canโt perform that action at this time.
0 commit comments