Skip to content

Commit 1105aaf

Browse files
committed
Runtime: 7 ms (Top 98.3%) | Memory: 13.26 MB (Top 67.3%)
1 parent b668fc2 commit 1105aaf

File tree

1 file changed

+12
-36
lines changed

1 file changed

+12
-36
lines changed
Lines changed: 12 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,14 @@
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-
2nd 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%)
302

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:
347
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...

0 commit comments

Comments
 (0)