본문으로 건너뛰기

226. Invert Binary Tree

· 약 1분
Seokjae Lee
Software engineer

원문: https://doljae.tistory.com/108

[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](https://leetcode.com/problems/invert-binary-tree/)

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



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