# 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
from collections import deque
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
# right = self.invertTree(root.right)
# left = self.invertTree(root.left)
# root.left = right
# root.right = left
# return root
q = deque([root])
while q:
curr = q.popleft()
curr.left, curr.right = curr.right, curr.left
if curr.left:
q.append(curr.left)
if curr.right:
q.append(curr.right)
return root
recursive way vs iterative way
트리 좌우반전하기
재귀로는 계속 들어가면서 left, right 를 바꿔준다
반복은 deque를 사용해서 일단 루트를 넣어주고 하나씩 pop하면서 양쪽을 바꿔주고 큐에 다시 넣어준다
'Dev > Algorithm' 카테고리의 다른 글
46. Permutations (Medium) (0) | 2024.11.11 |
---|---|
36. Valid Sudoku (Medium) (0) | 2024.11.10 |
121. Best Time to Buy and Sell Stock (Easy) (0) | 2024.11.08 |
26. Remove Duplicates from Sorted Array (Easy) (0) | 2024.11.08 |
138. Copy List with Random Pointer (Medium) (0) | 2024.11.07 |