File tree 1 file changed +12
-36
lines changed
scripts/algorithms/I/Invert Binary Tree 1 file changed +12
-36
lines changed Original file line number Diff line number Diff line change 1
- # Definition for a binary tree node.
2
- # class TreeNode:
3
- # def __init__(self, val=0, left=None, right=None):
4
- # self.val = val
5
- # self.left = left
6
- # self.right = right
7
- class Solution :
8
- def invertTree (self , root : Optional [TreeNode ]) -> Optional [TreeNode ]:
9
-
10
- def dfs (root ):
11
- if not root :
12
- return None
13
- root .left ,root .right = dfs (root .right ), dfs (root .left )
14
- return root
15
-
16
- return dfs (root )
17
-
18
-
19
- 2 nd Solution :
20
-
21
- class Solution :
22
- def invertTree (self , root : Optional [TreeNode ]) - > Optional [TreeNode ]:
23
-
24
- def helper (root ):
25
- if not root :
26
- return None
27
-
28
- left = helper (root .left )
29
- right = helper (root .right )
1
+ # Runtime: 7 ms (Top 98.3%) | Memory: 13.26 MB (Top 67.3%)
30
2
31
-
32
- root .left = right
33
- root .right = left
3
+ class Solution (object ):
4
+ def invertTree (self , root ):
5
+ # Base case...
6
+ if root == None :
34
7
return root
35
-
36
- helper (root )
37
-
38
- return root
8
+ # swapping process...
9
+ root .left , root .right = root .right , root .left
10
+ # Call the function recursively for the left subtree...
11
+ self .invertTree (root .left )
12
+ # Call the function recursively for the right subtree...
13
+ self .invertTree (root .right )
14
+ return root # Return the root...
You can’t perform that action at this time.
0 commit comments