Skip to content

Commit 1742c90

Browse files
committed
add solution: invert-binary-tree
1 parent 7a9c45a commit 1742c90

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

invert-binary-tree/dusunax.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'''
2+
# 226. Invert Binary Tree
3+
4+
switch left and right child of each node
5+
6+
## TC: O(N)
7+
8+
visit each node once
9+
10+
## SC: O(h)
11+
12+
h is height of tree
13+
14+
- best case: O(logN), balanced tree
15+
- worst case: O(N), skewed tree
16+
'''
17+
class Solution:
18+
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
19+
if not root:
20+
return None
21+
22+
root.left, root.right = root.right, root.left
23+
24+
self.invertTree(root.left)
25+
self.invertTree(root.right)
26+
27+
return root

0 commit comments

Comments
 (0)