Dev/Algorithm

226. Invert Binary Tree (Easy)

rryu09 2024. 11. 9. 17:42
# 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하면서 양쪽을 바꿔주고 큐에 다시 넣어준다