226. Invert Binary Tree

dasd412·2022년 3월 17일
0

코딩 테스트

목록 보기
20/71

문제 설명

Given the root of a binary tree, invert the tree, and return its root.

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

제약 조건

The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100

전체 코드

from collections import deque
# 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 bfs(self,current):
        queue=deque([current])
        
        while queue:
            node=queue.popleft()
            
            if node:
                node.left,node.right=node.right,node.left
                
                queue.append(node.left)
                queue.append(node.right)
        
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        self.bfs(root)
        return root

느낀 점

기본적이지만 꼭 다시 풀어볼 문제다. BFS 뿐만 아니라 DFS로도 풀이해봐야겠다.

profile
아키텍쳐 설계와 테스트 코드에 관심이 많음.

0개의 댓글