one line of code at a time

[leetcode] 226. Invert Binary Tree 파이썬 코드 본문

leetcode

[leetcode] 226. Invert Binary Tree 파이썬 코드

oloc 2024. 7. 3. 14:16

#트리

 

이진 트리에서 자식 노드의 좌, 우를 스왑하는 문제다. 

재귀적으로 호출하면서 좌, 우를 바꿔주면 된다. 

 

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if root is None:
            return root

        tmp = root.left
        root.left = root.right
        root.right = tmp

        self.invertTree(root.left)
        self.invertTree(root.right)

        return root

 

DFS 유형을 어려워하는 것 같다.