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
+ * 226. Invert Binary Tree
3
+ * Given the root of a binary tree, invert the tree, and return its root.
4
+ *
5
+ * https://leetcode.com/problems/invert-binary-tree/description/
6
+ *
7
+ */
8
+
9
+ class TreeNode {
10
+ val : number ;
11
+ left : TreeNode | null ;
12
+ right : TreeNode | null ;
13
+ constructor ( val ?: number , left ?: TreeNode | null , right ?: TreeNode | null ) {
14
+ this . val = val === undefined ? 0 : val ;
15
+ this . left = left === undefined ? null : left ;
16
+ this . right = right === undefined ? null : right ;
17
+ }
18
+ }
19
+
20
+ // O(n) time
21
+ // O(n) space
22
+ function invertTree ( root : TreeNode | null ) : TreeNode | null {
23
+ if ( ! root ) {
24
+ return null ;
25
+ }
26
+
27
+ const left = invertTree ( root . left ) ;
28
+ const right = invertTree ( root . right ) ;
29
+
30
+ root . left = right ;
31
+ root . right = left ;
32
+
33
+ return root ;
34
+ }
You can’t perform that action at this time.
0 commit comments