-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathinvert_binary_tree.py
36 lines (27 loc) · 933 Bytes
/
invert_binary_tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"""
Question: https://leetcode.com/problems/invert-binary-tree/
"""
from typing import Optional
class TreeNode:
"""
Definition for a binary tree node.
"""
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
"""
Approach: Use Recursive DFS to swap the children of the root.
"""
# Base case for recursion
if not root:
return None
# Swap the Children of the current `root`
root.left, root.right = root.right, root.left
# Run invertion on left and right subtrees
self.invertTree(root.left)
self.invertTree(root.right)
# At the end of all recursions, the final `root` will be the inverted tree.
return root