Zero to Hero
article thumbnail
Published 2021. 5. 3. 11:14
226. Invert Binary Tree Algorithm
 

Invert Binary Tree - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

1. Queue를 이용한 풀이

from collections import deque


class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return None
        if not root.left and not root.right:
            return root
        q = deque([])
        q.append(root)
        while q:
            print(q)
            cur = q.popleft()
            if not cur:
                continue
            q.append(cur.left)
            q.append(cur.right)
            cur.left, cur.right = cur.right, cur.left
        return root

2. 재귀를 이용한 풀이

class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return None
        root.left = self.invertTree(root.left)
        root.right = self.invertTree(root.right)
        root.left, root.right = root.right, root.left
        return root



자료구조의 입출력 연산의 오버헤드에 대해 생각해볼 수밖에 없는 문제.

'Algorithm' 카테고리의 다른 글

206. Reverse Linked List  (0) 2021.05.05
234. Palindrome Linked List  (0) 2021.05.04
141. Linked List Cycle  (0) 2021.05.03
53. Maximum Subarray  (0) 2021.05.02
101. Symmetric Tree  (0) 2021.05.02
profile

Zero to Hero

@Doljae

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!