Skip to content

Commit 5d7e549

Browse files
committed
solve: invertBinaryTree
1 parent 356e622 commit 5d7e549

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

invert-binary-tree/yolophg.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Time Complexity: O(N) - visit each node once.
2+
# Space Complexity: O(N) - skewed tree, recursion goes N levels deep.
3+
4+
class Solution:
5+
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
6+
if root is None:
7+
return root # If the tree is empty, just return None.
8+
9+
# swap left and right child nodes.
10+
root.left, root.right = root.right, root.left
11+
12+
# recursively invert left and right subtrees.
13+
if root.left:
14+
self.invertTree(root.left)
15+
if root.right:
16+
self.invertTree(root.right)
17+
18+
return root

0 commit comments

Comments
 (0)