File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * [Problem]: [226] Invert Binary Tree
3
+ * (https://leetcode.com/problems/invert-binary-tree/)
4
+ */
5
+
6
+ class TreeNode {
7
+ val : number ;
8
+ left : TreeNode | null ;
9
+ right : TreeNode | null ;
10
+ constructor ( val ?: number , left ?: TreeNode | null , right ?: TreeNode | null ) {
11
+ this . val = val === undefined ? 0 : val ;
12
+ this . left = left === undefined ? null : left ;
13
+ this . right = right === undefined ? null : right ;
14
+ }
15
+ }
16
+
17
+ function invertTree ( root : TreeNode | null ) : TreeNode | null {
18
+ // 시간복잡도 O(n)
19
+ // 공간복잡도 O(n)
20
+ function recursiveFunc ( root : TreeNode | null ) : TreeNode | null {
21
+ if ( root === null ) {
22
+ return null ;
23
+ }
24
+
25
+ const temp = root . left ;
26
+ root . left = invertTree ( root . right ) ;
27
+ root . right = invertTree ( temp ) ;
28
+
29
+ return root ;
30
+ }
31
+ // 시간복잡도 O(n)
32
+ // 공간복잡도 O(n)
33
+ function stackFunc ( root : TreeNode | null ) : TreeNode | null {
34
+ if ( root === null ) {
35
+ return null ;
36
+ }
37
+
38
+ const stack : Array < TreeNode | null > = [ root ] ;
39
+
40
+ while ( stack . length > 0 ) {
41
+ const node = stack . pop ( ) ! ;
42
+
43
+ if ( node === null ) {
44
+ continue ;
45
+ }
46
+
47
+ [ node . left , node . right ] = [ node . right , node . left ] ;
48
+ stack . push ( node . left , node . right ) ;
49
+ }
50
+
51
+ return root ;
52
+ }
53
+ }
You can’t perform that action at this time.
0 commit comments