File tree 1 file changed +34
-0
lines changed
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * https://leetcode.com/problems/invert-binary-tree/
3
+ * time complexity : O(n)
4
+ * space complexity : O(log N)
5
+ */
6
+
7
+ class TreeNode {
8
+ val : number
9
+ left : TreeNode | null
10
+ right : TreeNode | null
11
+ constructor ( val ?: number , left ?: TreeNode | null , right ?: TreeNode | null ) {
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
+ export const dfs = ( root : TreeNode | null , inverted : TreeNode | null ) : TreeNode | null => {
19
+ if ( ! root ) return null ;
20
+
21
+ const left = dfs ( root . left , inverted ) ;
22
+ const right = dfs ( root . right , inverted ) ;
23
+
24
+ root . left = right ;
25
+ root . right = left ;
26
+
27
+ return root ;
28
+ } ;
29
+
30
+ function invertTree ( root : TreeNode | null ) : TreeNode | null {
31
+ if ( ! root ) return null ;
32
+
33
+ return dfs ( root , new TreeNode ( 0 ) ) ;
34
+ } ;
You can’t perform that action at this time.
0 commit comments