LeetCode/Grind169

226. Invert Binary Tree

hyunkookim 2025. 4. 22. 03:29

226. Invert Binary Tree

 

# Definition for a binary tree node.
# class TreeNode:
#     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]:
        if not root:
            return None

        # 현재 왼, 오 바꾸고
        tmp = root.left
        root.left = root.right
        root.right = tmp
        
        # 자식들도 바꾸고
        root.left = self.invertTree(root.left)
        root.right = self.invertTree(root.right)
        return root

'LeetCode > Grind169' 카테고리의 다른 글

704. Binary Search  (0) 2025.04.22
242. Valid Anagram  (0) 2025.04.22
125. Valid Palindrome  (0) 2025.04.22
121. Best Time to Buy and Sell Stock ☆  (0) 2025.04.22
21. Merge Two Sorted Lists ☆  (0) 2025.04.22