Skip to content

Commit 5aa9758

Browse files
authored
Create 226_InvertBinaryTree.py
1 parent a525d9a commit 5aa9758

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

LeetCode/226_InvertBinaryTree.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""
2+
3+
4+
Runtime
5+
34 ms
6+
Beats
7+
84.37%
8+
Memory
9+
13.8 MB
10+
Beats
11+
56.90%
12+
"""
13+
14+
# Definition for a binary tree node.
15+
# class TreeNode:
16+
# def __init__(self, val=0, left=None, right=None):
17+
# self.val = val
18+
# self.left = left
19+
# self.right = right
20+
class Solution:
21+
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
22+
if root is None:
23+
return None
24+
return TreeNode(root.val,self.invertTree(root.right),self.invertTree(root.left))
25+
26+
27+
28+
"""
29+
Recursive Approach
30+
class Solution(object):
31+
def invertTree(self, root):
32+
# Base case...
33+
if root == None:
34+
return root
35+
# swapping process...
36+
root.left, root.right = root.right, root.left
37+
# Call the function recursively for the left subtree...
38+
self.invertTree(root.left)
39+
# Call the function recursively for the right subtree...
40+
self.invertTree(root.right)
41+
return root # Return the root...
42+
43+
"""
44+
45+

0 commit comments

Comments
 (0)