[leetcode] 226. Invert Binary Tree - Python

Heejun Kim·2022년 7월 5일
0

Coding Test

목록 보기
43/51

🔍 Problem

https://leetcode.com/problems/invert-binary-tree/


📰 문제풀이

  • 제한 시간: 15분
  • 성공 여부: 실패
  • 실패 원인: 아직 Python의 list node 자료구조에 익숙하지 않다.

📃 Solving Process

  1. list node로 연결되어 있기 때문에, left와 right의 노드가 자식을 갖고 있지 않을 때까지 재귀적으로 주소값을 바꿔주면 된다.

💻 Code

# 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 root is None:
            return None
        root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
        return root

⏱ Time Complexity

  • 이진 트리의 모든 노트 탐색은 트리의 높이만큼 탐색하기 때문에 O(logN)만큼의 시간 복잡도가 예상된다.

💾 Space Complexity

  • 재귀 함수로 계속 호출하기 때문에 모든 노드를 탐색하는 만큼의 공간이 필요해 O(N)이다.

0개의 댓글